Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP egrep_replace

Status
Not open for further replies.

mes123

Programmer
Jul 29, 2005
62
0
0
GB
I'm trying to use egrep_replace to scan a series of string and replace certain words in certain contexts. However, regex isn't my strong point and I can't get it to work.

If my the word I want to replace is 'cat' with 'mouse' but preserving some of the surrounding characters if they are allowed.

examples:
1: "a cat box" should give "a mouse box"
2: "a cat, box" -> "a mouse, box"
3: "a x.cat box" -> "a x.mouse box"
4: "a x.cat, box" -> "a x.mouse, box"
5: "a bigcat box" -> "a bigcat box"
6: "a catnap box" -> "a catnap box"

so if my target word has a space or dot before and a space or comma after then it should be replace preserving the characters before and after.

I've read a few online tutorials about regex, but still can't seem to make this work no matter what I try.
 
I've made some progress

I've made some progress...

ereg_replace('([. ])cat([, ])', '\1mouse\2', $string);
the two [ ] contain either a dot or comma and a space

1: "a cat box" gives "a mouse box" - OK
2: "a cat, box" -> "a cat, box" - STILL NOT RIGHT
3: "a x.cat box" -> "a x.mouse box" - OK
4: "a x.cat, box" -> "a x.mouse, box" - OK
5: "a bigcat box" -> "a bigcat box" - OK
6: "a catnap box" -> "a catnap box" - OK

cannot understand why example 2 won't work.
 
I prefer PHP's perl-compatible regular expressions to the POSIX-extended. The PHP online manual states that the preg_ functions have several features the ereg_ functions do not.

Code:
<?php
$cat_array = array (
	1 => array (0 => 'a cat box'),
	2 => array (0 => 'a cat, box'),
	3 => array (0 => 'a x.cat box'),
	4 => array (0 => 'a x.cat, box'),
	5 => array (0 => 'a bigcat box'),
	6 => array (0 => 'a catnap box'),
);

foreach ($cat_array as $key => $value)
{
	$cat_array[$key][1] = preg_replace ('/(\b)cat(\b)/', '$1mouse$2', $value[0]);
}

print '<pre>';
print_r ($cat_array);
?>

outputs:

[tt]Array
(
[1] => Array
(
[0] => a cat box
[1] => a mouse box
)

[2] => Array
(
[0] => a cat, box
[1] => a mouse, box
)

[3] => Array
(
[0] => a x.cat box
[1] => a x.mouse box
)

[4] => Array
(
[0] => a x.cat, box
[1] => a x.mouse, box
)

[5] => Array
(
[0] => a bigcat box
[1] => a bigcat box
)

[6] => Array
(
[0] => a catnap box
[1] => a catnap box
)

)[/tt]


Want the best answers? Ask the best questions! TANSTAAFL!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top