[英]php pattern matching
I want to get the part of the string before the last occurance of "-", 我想在最后一次出现“-”之前获取字符串的一部分,
for example, 例如,
$string1 = 'a-b-c-de-f-gfgh';
I want to get this part returned: abc-de-f. 我想返回此部分:abc-de-f。 Of course, I don't know the length of the last part.
当然,我不知道最后一部分的长度。
What is the easy way to do it? 简单的方法是什么?
Thank you 谢谢
echo substr ($string1, 0, strrpos ($string1, '-'));
strrpos()查找子字符串的最后一次出现-在这种情况下,substr()按照strrpos()的定义,将原始字符串从第0个字符拆分到第n个字符
get the last occurrence of -
using $x = strrpos($string1,'-');
得到最后一次
-
使用$x = strrpos($string1,'-');
then use substr()
to return the decired string from 0 to $x 然后使用
substr()
返回从0到$ x的字符串
echo substr ($string1, 0, $x);
As an alternative to the other posters: 替代其他海报:
preg_match('/(.*)-[^-]+/', 'a-b-c-de-f-gfgh', $result);
Result: 结果:
Array
(
[0] => a-b-c-de-f-gfgh-a
[1] => a-b-c-de-f-gfgh
)
Though I like Jeroens solution more. 虽然我更喜欢Jeroens解决方案。
您可以删除最后一部分:
$string = preg_replace("|-[^-]+$|", "", $string);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.