简体   繁体   中英

Preg_replace with regex and forward slash

Here is the code:

$string = "/My-Item-Here-p/sb-p36abbg.htm";
$str = preg_replace('/^.*-p\s*/', '', $string);
$str = substr($str, 1);
echo $str;

This spits out 6abbg.htm , I would like to have it to only remove everything before and including the "-p/" (note with forward slash).

So I would like it to spit out sb-p36abbg.htm

Try this regex: /^.*-p\\/(.*)$/

<?php
$sourcestring="/My-Item-Here-p/sb-p36abbg.htm";
echo preg_replace('/^.*-p\/(.*)$/','\1',$sourcestring);
?>

Codepad link.

I see no reason for you to use regex in that specific case. Just use strpos and substr .

$string = "/My-Item-Here-p/sb-p36abbg.htm";
$str = substr($string, strpos($string, '-p/') + 3);
echo $str;

Take into account that using regular expressions where they aren't really needed is a waste of computation resources.

$string = "/My-Item-Here-p/sb-p36abbg.htm";
$str = preg_replace('/^.*?(?=-p\/)', '', $string);

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.

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