[英]How to delete a piece of string in PHP using regular expressions?
我是PHP新手,今天发现了这个问题。 我有这个字符串:
442_38489_ext/index.php
我想删除一部分字符串:从其结尾到第一个反斜杠(在本例中为/index.php),仅在PHP中使用正则表达式。
有没有办法做到这一点? 我尝试了这段代码,但它什么也没做:
preg_replace("/\/(.+?)$/", '', $something_not_important);
你知道我的错误在哪里吗?
对我来说效果很好...
<?php
$something_not_important = '442_38489_ext/index.php';
$something_changed = preg_replace("/\/(.+?)$/", '', $something_not_important);
var_dump($something_changed);
上面的代码输出为:
string(13) "442_38489_ext"
也许您没有将调用的返回值分配给preg_replace()
?
您可以为具体情况使用dirname
,也可以使用'~/[^/]*$~'
类的正则表达式:
$something_not_important = "/more_here/442_38489_ext/index.php";
$s2 = dirname($something_not_important);
echo $s2 . "\n";
$s3 = preg_replace("~/[^/]*$~", '', $something_not_important);
echo $s3;
参见PHP演示
的/[^/]*$
模式匹配/
,然后0+比其他字符/
可达串(的末端$
)。
另外,不要忘记将值分配给变量,否则将不会更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.