简体   繁体   English

PHP substr经过一定的char,一个substr + strpos优雅的解决方案?

[英]PHP substr after a certain char, a substr + strpos elegant solution?

let's say I want to return all chars after some needle char 'x' from: 假设我想在一些针char'x 'x'之后返回所有字符:

$source_str = "Tuex helo babe" . $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. 不使用regexp不会使它更优雅,也可能更慢。

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). 因为当找不到'x'时, strpos返回FALSE (而不是JS中的-1 )。 FALSE would evaluate to zero, and 1st char would be always cut off. FALSE将评估为零,并且第一个字符将始终被切断。

Thanks, 谢谢,

Your first approach is fine: Check whether x is contained with strpos and if so get anything after it with substr . 你的第一种方法很好:检查strpos是否包含x ,如果是,则使用substr获取任何内容。

But you could also use strstr : 但你也可以使用strstr

strstr($str, 'x')

But as this returns the substring beginning with x , use substr to get the part after x : 但是当它返回 x开头的子字符串 ,使用substr来获取x之后的部分:

if (($tmp = strstr($str, 'x')) !== false) {
    $str = substr($tmp, 1);
}

But this is far more complicated. 但这要复杂得多。 So use your strpos approach instead. 所以请改用你的strpos方法。

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. ternary operator在5.3中进行了调整,以实现这一点。

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. 从PHP 5.3开始,可以省略三元运算符的中间部分。 Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise. 表达式expr1?:expr3如果expr1的计算结果为TRUE则返回expr1,否则返回expr3。

NB. NB。 ltrim will trim multiple matching characters at the start of the string. ltrim将在字符串的开头修剪多个匹配的字符。

if(strpos($source_str, 'x') !== FALSE )
   $source_str = strstr($source_str, 'x');

Less elegant, but without x in the beginning: 不太优雅,但开头没有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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM