I need help with preg_replace function

Good day phphelp,

I am currently studying preg_replace function

below are my code

index.html
[php]

Age:
Language:
[/php]

check.php
[php]<?php

$age=$_POST[‘age’];
$language=$_POST[‘language’];

$reference=array();
$reference[0]="/age/";
$reference[1]="/language/";

$replace=array();
$replace[0]=$age;
$replace[1]=$language;

$text = <<< heredoc

Age age
Language language
heredoc;

echo preg_replace($reference,$replace,$text);

?>[/php]

Input

Age: 12
Language: English

Output

Age 12
Langu12 langu12

My problem is the text “age” in “language” is also replaced by the input of what is being input in the text field “age”…

so how can I only replace the word “age”?? not including the “age” in “language”?

Thanks and regards :slight_smile:

You have to do a Word boundarys “\b” and I would also do case insenstivity “i”

Change This:
[php]echo preg_replace($reference,$replace,$text);[/php]

To:
[php]echo preg_replace("/\b" . $reference . “\b/i”,$replace,$text);[/php]

See the difference?

You can read about it here:

http://www.php.net//manual/en/function.preg-match.php

Thanks Topcoder! it worked, I was also looking for the list of regex :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service