0

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

5
  • Is preg_replace a must? Or are you open to other options? Commented Nov 6, 2012 at 16:08
  • Then add it. And escape if you wan't to keep your delimiters. Commented Nov 6, 2012 at 16:08
  • All you need is echo basename($string); Commented Nov 6, 2012 at 16:10
  • What if there are 2 or more instances of -p/ in the source string? Do you want to keep the smallest or the bigger substring? Commented Nov 6, 2012 at 16:11
  • there will always only be one instance of -p/ Commented Nov 6, 2012 at 16:13

3 Answers 3

1

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

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

Codepad link.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.