I have a string that begins with an empty space and a +
sign :
$s = ' +This is a string[...]';
I can't figure out how to remove the first +
sign using PHP. I've tried ltrim
, preg_replace
with several patterns and with trying to escape the +
sign, I've also tried substr
and str_replace
. None of them is removing the plus sign at the beginning of the string. Either it doesn't replace it or it remplace/remove the totality of the string. Any help will be highly appreciated!
Edit : After further investigation, it seems that it's not really a plus sign, it looks 100% like a +
sign but I think it's not. Any ideas for how to decode/convert it?
Edit 2 : There's one white space before the +
sign. I'm using get_the_excerpt
Wordpress function to get the string.
Edit 3 : After successfully removing the empty space and the +
with substr($s, 2);
, Here's what I get now :
$s == '#43;This is a string[...]'
Wiki : I had to remove 6 characters, I've tried substr($s, 6);
and it's working well now. Thanks for your help guys.
ltrim has second parameter
$s = ltrim($s,'+');
edit:
if it is not working it means that there is sth else at the beginning of that string, eg. white spaces. You can check it by using var_dump($s);
which shows you exactly what you have there.
You can use explode
like this:
$result = explode('+', $s)[0];
What this function actually does is, it removes the delimeter you specify as a first argument and breaks the string into smaller strings whenever that delimeter is found and places those strings in an array.
It's mostly used with multiple ocurrences of a certain delimeter but it will work in your case too.
For example:
$string = "This,is,a,string";
$results = explode(',', $string);
var_dump($results); //prints ['This', 'is', 'a', 'string' ]
So in your case since the plus sign appears ony once the result is in the zero index of the returned array (that contains only one element, your string obviously)
Here's a couple of different ways I can think of
$string = str_replace('+', '', $string);
$string = preg_replace('/^\+/', '', $string);
$string = ltrim($string, '+');
$string = substr($string, 1);
You can use ltrim() or substr(). For example :
$output = ltrim($string, '+');
or you can use
$output = substr($string, 1);
try this
<?php
$s = '+This is a string';
echo ltrim($s,'+');
?>
You can remove multiple characters with trim. Perhaps you were not re-assigning the outcome of your trim function.
<?php
$s = ' +This is a string[...]';
$s = ltrim($s, '+ ');
print $s;
Outputs:
This is a string[...]
ltrim
in the above example removes all spaces and addition characters from the left hand side of the original string.