hello!
I want to replace some words that is not bracketed
for exapmle:
I want to replace word 'ONE' with word 'TWO' in this string
'ONE other other other ONE (dont replace here ONE) ONE string (no ONE no) ONE'
to become :
'TWO other other other TWO (dont replace here ONE) TWO string (no ONE no) TWO '
Help!
Moderator: General Moderators
-
kingofnumbers
- Forum Newbie
- Posts: 6
- Joined: Thu Dec 23, 2010 9:35 pm
Re: Help!
please, I need help!
as soon as possible
as soon as possible
- ridgerunner
- Forum Contributor
- Posts: 214
- Joined: Sun Jul 05, 2009 10:39 pm
- Location: SLC, UT
Re: Help!
This script does what you want:
Hope this helps!

Code: Select all
<?php // test.php 20101226_100
$re = '/ # regex to match matching (possibly nested) parentheses.
( # $1: Capture whole match for PREG_SPLIT_DELIM_CAPTURE
\( # Open outermost parentheses.
(?: # Group alternatives of parentheses contents.
[^()]++ # One or more non-parentheses.
| (?R) # or a nested set of parentheses.
)*+ # Zero or more contents alternatives.
\) # Close outermost parentheses.
)
/x';
$data = 'ONE other other other ONE (dont replace here ONE) ONE string (no ONE no) ONE';
$w1 = 'ONE'; // Word to be replaced.
$w2 = 'TWO'; // Word to be substituted.
// Split string into parentheses and non-parentheses chunks.
$parts = preg_split($re, $data, -1, PREG_SPLIT_DELIM_CAPTURE);
$count = count($parts);
for ($i = 0; $i < $count; $i++) { // Loop through all chunks.
if ($parts[$i][0] != '(') { // Do replace if this a non-() chunk.
$parts[$i] = preg_replace('/\b'.$w1.'\b/', $w2, $parts[$i]);
}
}
$newdata = implode($parts); // Put humpty-dumpty back together again.
echo $newdata;
?>-
kingofnumbers
- Forum Newbie
- Posts: 6
- Joined: Thu Dec 23, 2010 9:35 pm
Re: Help!
Thanks, it works!