Re: looping through text with array_key_exists function



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


.



Relevant Pages

  • Re: looping through text with array_key_exists function
    ... This gives me one large string that I can easily insert into a webpage. ... // start replacing; the special characters will generate invalid image ... you will only have to maintain the $special array and leave the ...
    (alt.php)
  • Re: Cruise ship on the seas of time
    ... tags, let alone the s. ... You did invent <tab>, as far as I can tell. ... to use special characters, since many transmission protocols will mangle ...
    (rec.arts.sf.written)
  • Re: search strings using foreign characters
    ... special characters and replacing with standard ones when searching our ... try replacing all the special characters with _. ...
    (microsoft.public.sqlserver)
  • Re: search strings using foreign characters
    ... special characters and replacing with standard ones when searching our ... like 'Jose' as well as 'José'. ... as a matter of fact, ... try replacing all the special characters with _. ...
    (microsoft.public.sqlserver)
  • Re: tclsoap illegal characters
    ... so we ended up writing a parser to look for those special characters in ... values and "solve" the problem by replacing with something else or a ... Kind regards ...
    (comp.lang.tcl)