preg_replace()仅字符串的特定部分 [英] preg_replace() Only Specific Part Of String
本文介绍了preg_replace()仅字符串的特定部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我总是在使用正则表达式时遇到麻烦,例如,我基本上有一个网址:
I always have trouble with regex, I basically have a url, for example:
http://somedomain.com/something_here/bla/bla/bla/bla.jpg
我需要的是preg_replace(),用空字符串替换something_here
,并保持其他所有内容不变.
What I need is a preg_replace() to replace the something_here
with an empty string, and leave everything else in tact.
我尝试了以下方法,它替换了错误的部分:
I have tried the following and it replaces the wrong parts:
$image[0] = preg_replace('/http:\/\/(.*)\/(.*)\/wp-content\/uploads\/(.*)/','$2' . '',$image[0]);
这最终只剩下我要替换的部分,而不是实际替换它!
This ends up leaving only the part I want to replace, rather than actually replacing it!
推荐答案
以下代码基于您提供的描述:
The following code is based on the description you provided:
$url = 'http://somedomain.com/something_here/bla/bla/bla/bla.jpg';
$output = preg_replace('#^(https?://[^/]+/)[^/]+/(.*)$#', '$1$2', $url);
echo $output; // http://somedomain.com/bla/bla/bla/bla.jpg
说明:
-
^
:匹配行的开头 -
(
:开始匹配组1-
https?://
:匹配http或https协议 -
[^/]+
:匹配/
以外的任何内容一次或多次 -
/
:匹配/
^
: match begin of line(
: start matching group 1https?://
: match http or https protocol[^/]+
: match anything except/
one or more times/
: match/
-
.*
:匹配任何零次或多次(贪婪)
.*
: match anything zero or more times (greedy)
这篇关于preg_replace()仅字符串的特定部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-
查看全文