[英]PHP substr after a certain char, a substr + strpos elegant solution?
假设我想在一些针char'x 'x'
之后返回所有字符:
$source_str = "Tuex helo babe"
。
通常我会这样做:
if( ($x_pos = strpos($source_str, 'x')) !== FALSE )
$source_str = substr($source_str, $x_pos + 1);
你知道更好/更聪明(更优雅的方式)吗?
不使用regexp不会使它更优雅,也可能更慢。
不幸的是我们做不到:
$source_str = substr(source_str, strpos(source_str, 'x') + 1);
因为当找不到'x'
时, strpos
返回FALSE
(而不是JS中的-1
)。 FALSE
将评估为零,并且第一个字符将始终被切断。
谢谢,
你的第一种方法很好:检查strpos
是否包含x
,如果是,则使用substr
获取任何内容。
但你也可以使用strstr
:
strstr($str, 'x')
但是当它返回以 x
开头的子字符串时 ,使用substr
来获取x
之后的部分:
if (($tmp = strstr($str, 'x')) !== false) {
$str = substr($tmp, 1);
}
但这要复杂得多。 所以请改用你的strpos
方法。
正则表达式将使它更优雅:
// helo babe
echo preg_replace('~.*?x~', '', $str);
// Tuex helo babe
echo preg_replace('~.*?y~', '', $str);
但你总是可以试试这个:
// 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);
我只需要这个,并努力将它保持在一条线上以获得乐趣:
ltrim(strstr($source_str, $needle = "x") ?: $source_str, $needle);
ternary operator
在5.3中进行了调整,以实现这一点。
从PHP 5.3开始,可以省略三元运算符的中间部分。 表达式expr1?:expr3如果expr1的计算结果为TRUE则返回expr1,否则返回expr3。
NB。 ltrim
将在字符串的开头修剪多个匹配的字符。
if(strpos($source_str, 'x') !== FALSE )
$source_str = strstr($source_str, 'x');
不太优雅,但开头没有x
:
if(strpos($source_str, 'x') !== FALSE )
$source_str = substr(strstr($source_str, 'x'),1);
在$item
的末尾附加一个' - ',因此它总是在' - '之前返回字符串,即使$item
不包含' - ',因为strpos默认返回第一次出现 ' - '的位置。
substr($item,0,strpos($item.'-','-'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.