PHP:如何在字符串中的某些关键字之前删除所有内容?
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/
我从循环函数中得到这些类型的结果, p>
C:/ wamp / www / xxx / core / page /
C:/ wamp / www / xxx / local / page /
code> pre>
但我该如何修剪 关闭核心 strong>或本地 strong>之前的任何内容,所以我只得到这些, p>
core / page /
local / page /
code> pre>
我使用 strstr code>,但我认为它只搜索固定的关键字,我有两个,更多的关键字要匹配,
$ string ='C:/ wamp / www / xxx / local / page /';
$ output = strstr($ string,'(local | core)') ;
var_dump($ output);
code> pre>
我尝试使用 preg_replace code>, p>
var_dump(preg_replace('#/(core | local)/.*# si','/',$ string));
code> pre>
它给了我 前部 - C:/ wamp / www / xxx / code> p>
div>
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);
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.
Your code will be like:
$sData = 'C:/wamp/www/xxx/local/page/';
$sResult = preg_replace('/^(.*?)\/(core|local)\/(.*?)$/', '$2/$3', $sData);
$output = substr($string, strpos($string,'local/')+strpos($string,'core/'));
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 useecho ltrim($dir, "C:/wamp/www/xxx/");
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);