PHP Regular Expression
Category: Computers > Algorithms
Asked by: resipsadude-ga
List Price: $20.00
18 Jun 2006 08:17 PDT
Expires: 18 Jul 2006 08:17 PDT
Question ID: 739121
I need to know how, using a regular expression, to replace the term "sentence" in a string variable with "replacement", but the term "sentence" should not be replaced with anything if it is in HTML code (i.e, in between "<" and ">"). To be specific, for example, we start with $htmlstart and should end with $htmlend. $htmlstart="<html><head><body>Here is a sentence.<a href="/sentence.html>Link</a></body></html>" $htmlend="<html><head><body>Here is a replacement.<a href="/sentence.html>Link</a></body></html>" The regular expression should work with eregi_replace or preg_replace, or any command in PHP 4.3.10 or greater. Please provide the whole PHP command including the regular expression. Thanks for your help.
Re: PHP Regular Expression
Answered By: palitoy-ga on 19 Jun 2006 02:18 PDT
Hello resipsadude-ga, Thank-you for your question. This question is one of those puzzles that looks simple at a first glance but is more tricky once you try to implement it. The idea is based upon the principle of highlighting text in an HTML document that is often used on webpages such as search engines. The way I approached this subject was to build a regular expression that attempted to match a > character (first match) followed by a string of characters (second match) and finally a < character (third match). The second match indicates any words that appear on the screen and should not include any coding. I could then use the str_replace function in PHP to replace the words required in the second match (the string of characters). It is quite difficult to describe in words but hopefully when you see the code you will be able to see this. Here is my solution to this problem: <? $htmlstart='<html><head><body>Here is a sentence.<a href="/sentence.html">Link</a></body></html>'; print "<p>This is the original \$htmlstart:<br />$htmlstart</p>"; $phrase_to_be_replaced = "sentence"; $replacement_phrase = "replacement"; $htmlstart = preg_replace("/(>|^)([^<]+)(?=<|$)/esx","'\\1'.str_replace('$phrase_to_be_replaced', '$replacement_phrase', '\\2')",$htmlstart); print "<p>This is the altered \$htmlstart:<br />$htmlstart</p>"; ?> If you require any further assistance on this subject please do not hesitate to ask.
rated this answer:
and gave an additional tip of:
Works like a charm. Thank you very much. :)
Re: PHP Regular Expression
From: palitoy-ga on 20 Jun 2006 01:20 PDT
Thank-you for the 5-star rating and tip! They are both appreciated.
If you feel that you have found inappropriate content, please let us know by emailing us at email@example.com with the question ID listed above. Thank you.
|Search Google Answers for|