Reputation: 113
I need to remove all characters from a string after a particular character from the end. The below code works when it contains only one # eg:
$variable = "8233 Station #2212";
echo trim(substr($variable, 0, strpos($variable, "#")));
result: "8233 Station"; But if the string contains more than one # I need to avoid the strings after the last #
$variable = "8233 Station #2211 #2212";
The result i need in the above situation is "8233 Station #2211"
Upvotes: 2
Views: 4231
Reputation: 2561
It can also be done with substr()
which extract the string from a string and strrpos()
which return last occurrence of a character, try like below:
<?php
$variable = "8233 Station #2211 #2212";
echo substr($variable, 0, strrpos($variable, "#"));
check the output here: https://eval.in/813032
Upvotes: 1
Reputation: 3302
strpos — Find the position of the first occurrence of a substring in a string
strrpos — Find the position of the last occurrence of a substring in a string
$variable = "8233 Station #2212 #2212";
echo trim(substr($variable, 0, strrpos($variable, "#")));
Upvotes: 1
Reputation: 16436
Use strrpos
to get position of last matching element
//$variable = "8233 Station #2212"; //8233 Station
$variable = "8233 Station #2211 #2212";
echo trim(substr($variable, 0, strrpos($variable, "#"))); //8233 Station #2211
Upvotes: 2