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,
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);
I needed just this, and striving to keep it on one line for fun came up with this:
ltrim(strstr($source_str, $needle = "x") ?: $source_str, $needle);
The ternary operator
was adapted in 5.3 to allow this to work.
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
NB. ltrim
will trim multiple matching characters at the start of the string.
if(strpos($source_str, 'x') !== FALSE )
$source_str = strstr($source_str, 'x');
Less elegant, but without x
in the beginning:
if(strpos($source_str, 'x') !== FALSE )
$source_str = substr(strstr($source_str, 'x'),1);
在$item
的末尾附加一个' - ',因此它总是在' - '之前返回字符串,即使$item
不包含' - ',因为strpos默认返回第一次出现 ' - '的位置。
substr($item,0,strpos($item.'-','-'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.