Dan
Dan

Reputation: 152

PHP - Find word in variable and replace with another

So I've got a script that basically takes input from a text area and I want to find a specific word in the variable (in the string) and replace it with another.

So far I've been getting all sorts of errors.

I want to for example find **contact and replace it with **/page/contact etc.

I'll keep trying and edit in the errors that I get here. I've no idea what I'm doing wrong.

edit 1

I'm getting

Warning: preg_replace() [function.preg-replace]: Unknown modifier 'a' in /path/.../.../*.php on line 57

When using

$string = preg_replace("**example", "**/page/example", $string);

Upvotes: 0

Views: 2196

Answers (3)

Zombiesplat
Zombiesplat

Reputation: 953

preg_replace modifiers are http://php.net/manual/en/reference.pcre.pattern.modifiers.php e,x,s,m and i

the first character in your pattern was the asterisk * followed by another then ex

**ex

which is all legitimate but the interpreter stopped at the unrecognized modifier a and showed the error.

a proper way to make this a preg_replace would be but * is also a reserved character so you need to escape it.

 preg_replace("/\*\*example/", "**/page/example", $string);

or

 preg_replace("~\*\*example~", "**/page/example", $string);

or for the **contact

 preg_replace("/\*\*contact/", "**/page/contact", $string);

Upvotes: 0

Kayce Basques
Kayce Basques

Reputation: 26017

It would be helpful to have more context. Give us the relevant PHP code that is performing this task for you, as well as a sample of the text content that you expect to receive, in addition to how you expect to receive that content (is it sent from the web via user input? Extracted from a CSV file? Etc.)

Are you looking for a way to replace general patterns of text, or do you know exactly which text you need to be replace? For example, given the example that you have provided (replacing **contact with **/page/contact) if you can expect this exact string then you can use any of the string replacement functions that PHP provides.

If you are working with general patterns of text then you may need to use regular expressions.

Upvotes: 0

Feek
Feek

Reputation: 650

Use str_replace

$string = str_replace('**contact', '**/page/contact', $string);

Upvotes: 2

Related Questions