You are here: Re: Complex replace in php 4 « PHP Programming Language « IT news, forums, messages
Re: Complex replace in php 4

Posted by Mike P2 on 05/01/07 20:13

On May 1, 6:54 am, Toby A Inkster <usenet200...@tobyinkster.co.uk>
wrote:
> Mike P2 wrote:
> > I assumed that if it were wrapped in an anchor tag there would be no
> > whitespace on the inside of the anchor tag. It won't replace the
> > following:
>
> > <a href="...">my car</a>
>
> > unless he takes out the character groups
>
> However, yours will replace:
>
> <a href="...">my car is very fuel-efficient</a>

Actually, it will not. '>' is not an accepted character in either
character group.

BTW, as I mentioned before, my idea assumes there will be no
whitespace on the ends of the content of the link if there is one
already. That can be fixed like this:

<?php
$search = 'my car';
$link = '...';
$string = 'my car is very fuel-efficient';

$string = str_ireplace( $search, " $search ", $string );
$string = preg_replace( '#(<a[^>]+>)(\s+)#i', '$2$1', " $string" );
$string = preg_replace( '#(\s+)</a>#i', '</a>$1', $string );
$string = preg_replace( "#([\s\(])$search([\s\)\.])#i", "$1<a
href='$link'>$search</a>$2", $string );

echo $string;
?>

What I thought of is to add those two extra preg_replace()s before the
main one that moves whitespace on edges from inside to outside of
anchor tags. The middle preg_replace() may be optional, since the last
one will not work if the words are butted up against the open tag
anyway. Finally, I just added that str_ireplace() so it can even
replace the keywords when next to or inside of some other tag. If you
think this is too slow, consider taking out case insensitivity or the
middle preg_replace() (or the first one maybe).

-Mike PII

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация