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 anythi开发者_如何转开发ng.
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). 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 );
精彩评论