使用 PHP preg_replace 替换两个字符串之间的值
我有一个脚本,可以以表格的形式将一些 HTML 拉入我的网页。我想使用 PHP preg_replace 替换 HTML 中包含的部分 URL。 URL 包含一些始终不同的文本。该 URL 在网页中并不唯一,但我要替换的 URL 仅出现在特定图像之前。
到目前为止,我的尝试(不起作用、可笑并且可能完全错误)如下:
$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 );
上面的示例尝试从页面上的单个 URL 中删除 &variable=1
。该 URL 在页面上出现多次,但仅在 image.gif
之前出现一次。 URL 中始终不同的部分由 .*\
表示以匹配任何内容。
有人可以提供一个工作示例吗?谢谢!
I have a script that pulls in some HTML to my webpage in the form of a table. I would like to replace part of a URL contained within the HTML using PHP preg_replace. The URL contains some text which is always different. The URL is not unique in the webpage, but the one I want to replace ONLY appears before a specific image.
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. The URL appears many times on the page, but only once directly before image.gif
. The part of the URL that is always different is represented by .*\
to match anything.
Can anybody produce a working example? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您已经非常接近了,但是您忘记了一些技术问题,例如在正则表达式周围使用分隔符(下面示例中的“|”)和使用引用(下面的 $1 和 $2)。如果下面的代码不起作用,请发布您尝试匹配的文本示例。
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). If the code below doesn't work please post an example of the text you're trying to match.