ToddN
ToddN

Reputation: 2961

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

Upvotes: 0

Views: 3170

Answers (3)

Ωmega
Ωmega

Reputation: 43663

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

Upvotes: 0

Kash
Kash

Reputation: 9019

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

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

Codepad link.

Upvotes: 1

iMoses
iMoses

Reputation: 4348

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.

Upvotes: 0

Related Questions