let's say I want to return all chars after some needle char 'x'
from:
$source_str = "Tuex helo babe"
.
Normally I would do this:
if( ($x_pos = strpos($source_str, 'x')) !== FALSE )
$source_str = substr($source_str, $x_pos + 1);
Do you know a better/smarter (more elegant way) to do this?
Without using regexp that would not make it more elegant and probably also slower.
Unfortunately we can not do:
$source_str = substr(source_str, strpos(source_str, 'x') + 1);
Because when 'x'
is not found strpos
returns FALSE
(and not -1
like in JS).
FALSE
would evaluate to zero, and 1st char would be always cut off.
Thanks,
$data = "123_String"; $whatIWant = substr($data, strpos($data, "_") + 1); echo $whatIWant; Php Get String After Character.
The strpos() function finds the position of the first occurrence of a string inside another string.
Use the substring() method to get the substring before a specific character, e.g. const before = str. substring(0, str. indexOf('_')); . The substring method will return a new string containing the part of the string before the specified character.
substr in PHP is a built-in function used to extract a part of the given string. The function returns the substring specified by the start and length parameter. It is supported by PHP 4 and above. Let us see how we can use substr() to cut a portion of the string.
Your first approach is fine: Check whether x
is contained with strpos
and if so get anything after it with substr
.
But you could also use strstr
:
strstr($str, 'x')
But as this returns the substring beginning with x
, use substr
to get the part after x
:
if (($tmp = strstr($str, 'x')) !== false) {
$str = substr($tmp, 1);
}
But this is far more complicated. So use your strpos
approach instead.
Regexes would make it a lot more elegant:
// helo babe
echo preg_replace('~.*?x~', '', $str);
// Tuex helo babe
echo preg_replace('~.*?y~', '', $str);
But you can always try this:
// helo babe
echo str_replace(substr($str, 0, strpos($str, 'x')) . 'x', '', $str);
// Tuex helo babe
echo str_replace(substr($str, 0, strpos($str, 'y')) . 'y', '', $str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With