PHP rtrim and ltrim trim more than intended

I need to remove Search -

from a page on my website. Below is an example of my code below:

Input:

$search = "Search - echelon";
$trim = "Search - ";

$result = ltrim($search,$trim);


echo $result;

      

Output:

lon

Desire output:

echelon

How can I do this, and why is it clipping more in my example above? Thank!

+1


source to share


5 answers


RTM . The second argument is treated as a set of characters to trim.

In this case:

S - in the list, trim it
e - in the list, trim it
a - in the list, trim it
r - in the list, trim it
c - in the list, trim it
h - in the list, trim it
_ - (space) in the list, trim it
- - in the list, trim it
_ - (space) in the list, trim it
e - in the list, trim it
c - in the list, trim it
h - in the list, trim it
e - in the list, trim it
l - NOT in the list, stop!

lon is left

      



Did you mean it?

$result = substr($search,strlen($trim));

      

+6


source


ltrim ( string $str [, string $character_mask ] )

- strip spaces (or other characters) from the beginning of the line. character_mask are the characters you want to remove.

How about str_replace

,



$result = str_replace($trim,"",$search);

      

+3


source


from PHP.net : ltrim - skip space (or other characters) from beginning of line

So it doesn't truncate the string, it truncates any of the characters entered ...

I would go with @ krishR's answer

+1


source


trim

truncates any of the characters you give it. He looks at each character separately and cuts them off, he doesn't look for the whole line. If you want to remove a line from the beginning if and only if it exists, do this:

$trimmed = preg_replace('/^Search - /', '', $search);

      

+1


source


// trim — Strip whitespace (or other characters) from the beginning and end of a string
// Example 
$ageTypes = ' Adult, Child, Kids, ';
// Output, removes empty string from both ends 
// Adult, Child, Kids,

// Rtrim  - Remove characters from the right side of a string: 
// Example 
$ageTypes = 'Adult, Child, Kids';
echo rtrim($ageTypes, ',');
// Output 

// Ltrim - Remove characters from the left side of a string: 
// Example 
$ageTypes = ',Adult, Child, Kids, ';
echo ltrim($ageTypes, ',');
// Adult, Child, Kids,

      

0


source







All Articles