简体   繁体   中英

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. 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!

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM