I'm new to PHP and today I found this problem. I have this string:
442_38489_ext/index.php
I want to delete a piece of the string: from end of it to first backslash (in this case /index.php), using only regular expressions in PHP.
Is there a way to do that? I tried this code but it does nothing:
preg_replace("/\/(.+?)$/", '', $something_not_important);
Do you know where my mistake is?
Works perfectly fine for me...
<?php
$something_not_important = '442_38489_ext/index.php';
$something_changed = preg_replace("/\/(.+?)$/", '', $something_not_important);
var_dump($something_changed);
The output of above code is:
string(13) "442_38489_ext"
Maybe you did not assign the return value of the call to preg_replace()
?
You may use dirname
for your concrete case, or use a regex like '~/[^/]*$~'
:
$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;
See the PHP demo
The /[^/]*$
pattern matches /
, then 0+ chars other than /
up to the end of string ( $
).
Also, do not forget to assign the value to a variable, or it will not get updated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.