By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,463 Members | 774 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,463 IT Pros & Developers. It's quick & easy.

highlighting regex matches

P: n/a
I'm trying to achieve the following:

start form entry
user enters form data and submits ($form_data)
preg_match_all data for $pattern, store matches in $match_arr
if one or more matches
display string back to user, with matched substrings in different
color/emphasis
start form entry again
else continue

my initial solution to recontructing the string:
// if 1 match
preg_replace ($pattern,'<em>'.$match_arr[0][0].'</em>',$form_data,1);
// if multiple matches
preg_replace ($pattern,'<em>'.$match_arr[0].'</em>',$form_data,-1);

...but the latter doesn't work the way I hoped. When the replace var is
an array $pattern also must be an array for preg_replace to use the
different array values in $replace.

Any ideas how to get around this problem in an elegant manner? Or an
alternative solution altogether? I searched for a function/solution
that tells me at which position preg_match_all() found a match, so I
can avoid the preg_replace altogether, but I haven't found any.

cheers,
Semi

May 23 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On 23.05.2007 15:37 se*******@inbox.com wrote:
I'm trying to achieve the following:

start form entry
user enters form data and submits ($form_data)
preg_match_all data for $pattern, store matches in $match_arr
if one or more matches
display string back to user, with matched substrings in different
color/emphasis
start form entry again
else continue

my initial solution to recontructing the string:
// if 1 match
preg_replace ($pattern,'<em>'.$match_arr[0][0].'</em>',$form_data,1);
// if multiple matches
preg_replace ($pattern,'<em>'.$match_arr[0].'</em>',$form_data,-1);

..but the latter doesn't work the way I hoped. When the replace var is
an array $pattern also must be an array for preg_replace to use the
different array values in $replace.

Any ideas how to get around this problem in an elegant manner? Or an
alternative solution altogether? I searched for a function/solution
that tells me at which position preg_match_all() found a match, so I
can avoid the preg_replace altogether, but I haven't found any.

cheers,
Semi
I think you're looking for PREG_OFFSET_CAPTURE flag (see preg_match_all
manual page).

--
gosha bine

extended php parser ~ http://code.google.com/p/pihipi
blok ~ http://www.tagarga.com/blok
May 23 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.