如何使用正则表达式在PHP中删除一段字符串?

如何使用正则表达式在PHP中删除一段字符串?,php,string,Php,String,我是PHP新手,今天我发现了这个问题。我有这个字符串: 442_38489_ext/index.php 我想删除一段字符串:从它的末尾到第一个反斜杠(在本例中为/index.php),在php中只使用正则表达式 有办法吗?我尝试了此代码,但它没有任何作用: preg_replace("/\/(.+?)$/", '', $something_not_important); 你知道我的错误在哪里吗?对我来说非常好 <?php $something_not_important = '442_

我是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);
可能您没有将调用的返回值分配给
preg\u replace()

您可以将其用于具体案例,或者使用类似于
'~/[^/]*$~'的正则表达式

$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;

/[^/]*$
模式匹配
/
,然后0+个字符,而不是
/
,直到字符串结尾(
$


另外,不要忘记将值赋给变量,否则它将不会更新。

那么,什么不起作用<代码>$new\u str=preg\u replace(“/\/(.+?)$/”,“,$something\u not\u important”)。但是使用正则表达式的更好选项是
“~/[^/]*$~”
。那dirname($s)呢?没人会恨你的:-)欢迎!Wiktor,当我试图打印包含修改过的字符串的变量时,它没有显示任何内容。阿卡莎,谢谢你!:)查看带有
dirname
的演示-嘿,Wiktor,它成功了!非常感谢你!当前正则表达式的问题是,它将删除多个
/
。如果stringWell中有多个
/
,则问题已经解决,但感谢您的回答!
$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;