![]() Topic awaiting preservation: Don't Replace a String If It's Inside a Tag (PHP) (Page 1 of 1) |
|
---|---|
Paranoid (IV) Mad Scientist From: Inside THE BOX |
![]() I've developed a fairly simple PHP module for my new site that allows me to input strings to be replaced with other strings. It's an easy way to add links to phrases or replace certain terms dynamically. (There's a bit more to it, but that's the basic idea.) |
Maniac (V) Mad Scientist with Finglongers From: Germany |
![]() your solution is pretty optimal, giving the constraint: don't use a real parser. |
Paranoid (IV) Inmate From: Madison, Indiana |
![]() What you're suggesting is something like code: $new_string1 = preg_replace(/source/, 'target', $string); $new_string2 = preg_replace(/<[^>]*target[^>]*>/, 'source', $new-string1);
code: preg_match_all('/([^<]*)(<[^>]*>)/', $string, $matches, PREG_SET_ORDER); $result_string = ''; foreach ($matches as $part) { $result_string .= preg_replace('/source/', 'target', $part[1]); $result_string .= $part[2]; } if (preg_match('/>([^<>]+)$/', $string, $matches)) { $result_string .= preg_replace('/source/', 'target', $matches[1]); }
|
Paranoid (IV) Inmate From: f(x) |
![]() code: preg_replace('#[^>]+(?=<[^/])#i','foo',$string)
code: foo<img src="file" alt="DONT_TOUCH">foo<a href="file">DONT_TOUCH</a>foo<div>DONT_TOUCH</div>
code: preg_replace('#[^>]+(?=<[^/])|[^>]+$#','foo',$string)
|
Paranoid (IV) Inmate From: Madison, Indiana |
![]() I may have misunderstood what he's asking for, but if the string contains code: $string = 'stuff and nonsense. stuff to replace. more stuff<tag atl="stuff not to touch">'
code: 'foo<tag atl="stuff not to touch">'
code: 'stuff and nonsense. foo. more stuff<tag atl="stuff not to touch">' |
Paranoid (IV) Inmate From: f(x) |
![]() I sorta meant for that to be more of an example that could be used towards the solution. A solution like this: code: <?php $string = 'stuff and nonsense. stuff to replace. more stuff<tag alt="stuff not to touch"> foo.'; $find = array('foo','stuff to replace'); $replace = array('bar','replaced'); preg_match_all('#[^>]+(?=<[^/])|[^>]+$#', $string, $matches, PREG_SET_ORDER); foreach ($matches as $val) { $string = str_replace($val[0],str_replace($find,$replace,$val[0]),$string); } echo $string; // Output: stuff and nonsense. replaced. more stuff<tag alt="stuff not to touch"> bar. ?> |
Neurotic (0) Inmate Newly admitted From: |
![]() I want to use this code but I only want to replace the first occurrence of $find in $string. How would I do this? |