Forum Moderators: coopster

Message Too Old, No Replies

preg match problem

         

omoutop

12:27 pm on Oct 4, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



in theory, an easy code
in real life.. something is messing things up

the simple code is:

$show_text = 'some string i get from db';
$var_show = 'some variable i get from db';

$my_url = '<a href="/'.$var1.'/'.$var2_web.'/index.htm" class="myclass">'.$var_show.'</a>';
$my_url = preg_quote ($my_url, '/');
$show_text = preg_replace($var_show, $my_url, $show_text, 1);


What i try to do is replace the first instance of $var_show with its link equivalent.

And all i get is:
Warning: preg_replace() [function.preg-replace]: Delimiter must not be alphanumeric or backslash

What am I missing?

penders

2:31 pm on Oct 4, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The delimiter is the character marking the start and end of the regular expression, often the '/' (forward slash) is used, but you can use other characters if you wish, as long as they match.

It looks like you are simply missing the delimiter?!

preg_replace('/'.$var_show.'/', ...

rocknbil

5:14 pm on Oct 4, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Right, or double quote it to interpolate the variables. . . .

$show_text = preg_replace("/$var_show/", $my_url, $show_text, 1);

Throw in the i modifier for case-insensitivity.

$show_text = preg_replace("/$var_show/i", $my_url, $show_text, 1);

omoutop

6:22 am on Oct 5, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



nice tips but still i miss something
ok, i follow your advice
no errors now, but i dont have the expectd results

Instead of turning my "keyword" into "keyword+link", i now get "/keyword/".

penders

9:47 am on Oct 5, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



$my_url = preg_quote ($my_url, '/'); <-- NOT REQD


You do not need to preg_quote() $my_url unless you are matching against $my_url (ie. if it part of your regular expression pattern). $my_url is just your replacement string.

Remove that line and it should work. However, depending on your data (or may be it's just good practise) you might need to preg_quote() $var_show, since that is the pattern you are matching against.
$var_show = preg_quote ($var_show, '/');