[英]Using PHP preg_replace to replace a value between two strings
I have a script that pulls in some HTML to my webpage in the form of a table. 我有一个脚本,该脚本以表格的形式将一些HTML提取到我的网页中。 I would like to replace part of a URL contained within the HTML using PHP preg_replace.
我想使用PHP preg_replace替换HTML中包含的一部分URL。 The URL contains some text which is always different.
该URL包含一些总是不同的文本。 The URL is not unique in the webpage, but the one I want to replace ONLY appears before a specific image.
该URL在网页中不是唯一的,但是我只想替换的URL出现在特定图像之前。
My (non working, laughable and probably completely wrong) attempt so far is as follows: 到目前为止,我的尝试(没有工作,可笑并且可能完全错误)如下:
$result = preg_replace( '/\http://www.mysite.com/script.php?&variable=1.*\<img src="http://www.mysite.com/images/image.gif"', 'http://www.mysite.com/script.php?.*\<img src="http://www.mysite.com/images/image.gif"', $result );
The above example attempts to remove &variable=1
from a single URL on the page. 上面的示例尝试从页面上的单个URL中删除
&variable=1
。 The URL appears many times on the page, but only once directly before image.gif
. 该URL在页面上显示多次,但在
image.gif
之前仅显示一次。 The part of the URL that is always different is represented by .*\\
to match anything. URL中始终不同的部分用
.*\\
表示,以匹配任何内容。
Can anybody produce a working example? 有人能提供一个可行的例子吗? Thanks!
谢谢!
I think you're pretty close but you forgot a few technical things like using delimiters around the regex (the '|' in the example below) and using references ($1 and $2 below). 我认为您已经很接近了,但是您忘记了一些技术性的东西,例如在正则表达式周围使用定界符(在下面的示例中为“ |”),并使用引用(在下面为$ 1和$ 2)。 If the code below doesn't work please post an example of the text you're trying to match.
如果以下代码不起作用,请发布您要匹配的文本示例。
$result = preg_replace('|http://www.mysite.com/script.php\?([^"]*)&variable=1([^<]*)<img src="http://www.mysite.com/images/image.gif"|', 'http://www.mysite.com/script.php?$1$2<img src="http://www.mysite.com/images/image.gif"', $result );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.