Page 1 of 1

preg_match - how to use this with variables?

Posted: Wed Aug 27, 2008 2:17 pm
by jbh
[editing for clarity and simplicity]

Basically, I have a function that is supossed to replace x number of instances of a word with another word

Thing is, when I use preg_replace with a variable ($firstword) I get php errors. It works when I HARD CODE it, but I obviously
cannot do that as I will be looping through a db. How can I legally do the following?

$content=preg_replace($firstword, $replacement, $content, $num);

What syntax would work so it can sniff out $firstword (a value pulled from a database, field 'keyword')
I cannot find it anywhere, on php.net/etc. I just want to use variables, not hard coded values, with preg_match.

Thanks for your time.

PS.
And in case you want to know why I use preg_match and not str_replace, it's because I am offering this to php4 web servers
and I need to specify the NUMBER of replacements for each word found. In this example, the var $num specifies this.

Re: preg_match - how to use this with variables?

Posted: Wed Aug 27, 2008 4:13 pm
by jbh
Found it. For those who are also confused a bit with this function, I did this:

$content=preg_replace("/($k)/i",$replacement, $content, $num);

Notice "/($k)/i" in place of $firstword, which was my dilema.

I hope this helps some of you beginners. Although I am experienced I always have a mental block with
regexp and the like. Don't know why.