Search code examples
phpregexpreg-replacestrstrphp-5.4

PHP: How to trim off everything before certain keywords in strings?


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/


Solution

  • 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.