You are here: Re: looping through text with array_key_exists function « All PHP « IT news, forums, messages
Re: looping through text with array_key_exists function

Posted by Janwillem Borleffs on 10/10/68 11:51

drako wrote:
> I thought using "preg_match" would work - i.e.
>
> if(preg_match('/([a-z0-9])/', $text)) {preg_replace('/([a-z0-9])/',
> '<img src="$1.jpg" />', $text); }
>

This is superfluous use of preg_* functions, as you can use preg_replace
without the preg_match.

Tricky thing, however, is that img tags contain spaces and you only want to
replace spaces outside the tags.

The following solution offers a workaround for this problem:

$text = 'hello world!';

// replace special cases
$special = array(
' ' => 'space.jpg',
'!' => 'exclamation.jpg',
'_' => 'underscore.jpg'
);

// generate a string from the special characters
$specialchars = preg_quote(implode('', array_keys($special)), '/');

// start replacing; the special characters will generate invalid image
markers (like "_.jpg"),
// which will be replaced during the the second run of preg_replace
$text = preg_replace('/([a-z0-9' . $specialchars . '])/', '<img src="$1.jpg"
/>', $text);

// replace special characters in the img src attributes
$text = preg_replace('/([' . $specialchars . ']).jpg/e', '$special[\'$1\']',
$text);

This way, you will only have to maintain the $special array and leave the
other code as is.

There are other ways of doing this, but the above should give you a push in
the right direction.


JW

 

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

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