Question

I have these type of results from a loop function,

C:/wamp/www/xxx/core/page/
C:/wamp/www/xxx/local/page/

But how can I trim off anything before core or local, so I get these only,

core/page/
local/page/

I use strstr, but I think it search for a fixed keyword only, I have two, many more keywords to match,

$string = 'C:/wamp/www/xxx/local/page/';
$output = strstr($string, '(local|core)');
var_dump($output);

I tried with preg_replace,

var_dump(preg_replace('#/(core|local)/.*#si', '/', $string));

it gives me the front part - C:/wamp/www/xxx/

Was it helpful?

Solution 2

You can use preg_replace like this:

$output = preg_replace('~^.*?((?:core|local).*$)~i', "$1", $string);

or

$output = preg_replace('~^.*?(?=core|local)~i', '', $string);

If you want to match strictly up to the folder core or local, you can use this:

$output = preg_replace('~^.*?/(?=(?:core|local)/)~i', '', $string);

Viper-7 demo


To your question:

var_dump(preg_replace('#/(core|local)/.*#si', '/', $string));

This will match /(core|local)/.* and replace it by /, which is not really what you're looking for, because you actually have to match what is before this. My first regex here is an example of that: it will match everything before (?:core|local) and then capture everything which comes afterwards into a capture group, which I'm referring to when using the backreference $1.

And well, because of the votewar going here... I added the forward slashes in the match, and you will be using less memory if you don't use a capture group at all (but using a lookahead), hence how I came to the last regex.

OTHER TIPS

Your code will be like:

$sData   = 'C:/wamp/www/xxx/local/page/';
$sResult = preg_replace('/^(.*?)\/(core|local)\/(.*?)$/', '$2/$3', $sData); 

Use preg_match()

<?
    $dir = "C:/wamp/www/xxx/core/page/";
    preg_match("#^.*?/((?:local|core).*/)$#i",$dir,$match);
    echo $match[1];
?>

If the first bit of the string is always the same you can use
echo ltrim($dir, "C:/wamp/www/xxx/");

$output = substr($string, strpos($string,'local/')+strpos($string,'core/'));

You can do it in a different way using str_replace. Check below.

$string = 'C:/wamp/www/xxx/local/page/';
$output = str_replace('C:/wamp/www/xxx/' , '' , $string);
var_dump($output);

It will simply trim off the left side string.

preg_replace('/.*(core|local)/', "$1", $string);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top