preg_replace won't change data

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

preg_replace won't change data

Post by someguyhere »

The preg_replace I'm using isn't working. Basically, it's supposed to take a particular word within the content, and wrap a link to and internal page around the word. The spaces on each side of each variable are so that it only links the actual word, not a coincidental occurrence of the letters within another word.

Code: Select all

		$paragraph1 = preg_replace('/ $keyword_phrase /', '/ $in_content_link /', $paragraph1, 1);
If it makes a difference, the variables will all contain strings, so

$keyword_phrase might be something like "Contact Us "

$in_content_link might be something like "/contact-us/" or "http://www.domain.com/contact-us/"
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: preg_replace won't change data

Post by cpetercarter »

You need to change two things.

First, php will recognise variables inside double quoted strings, but not single quoted strings.

Second, you need the delimiters (/) for the beginning and the end of the pattern you are searching for only for the first parameter, not for the second.

So, the following should work.

Code: Select all

paragraph1 = preg_replace("/ $keyword_phrase /", " $in_content_link ", $paragraph1, 1);
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

Re: preg_replace won't change data

Post by someguyhere »

Thank you
Post Reply