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 |
posted 12-03-2007 03:53
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 |
posted 12-03-2007 08:52
your solution is pretty optimal, giving the constraint: don't use a real parser. |
Paranoid (IV) Inmate From: Madison, Indiana |
posted 12-03-2007 19:32
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) |
posted 12-06-2007 08:41
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 |
posted 12-06-2007 22:17
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) |
posted 12-07-2007 00:24
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: |
posted 01-06-2009 23:21
I want to use this code but I only want to replace the first occurrence of $find in $string. How would I do this? |