0

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!

1 Answer 1

1

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 );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.