Page 1 of 1

Help!

Posted: Thu Dec 23, 2010 9:47 pm
by kingofnumbers
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 '

Re: Help!

Posted: Sat Dec 25, 2010 2:44 am
by kingofnumbers
please, I need help!
as soon as possible

Re: Help!

Posted: Sun Dec 26, 2010 11:40 am
by ridgerunner
This script does what you want:

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;
?>
Hope this helps!
:)

Re: Help!

Posted: Sun Dec 26, 2010 1:55 pm
by kingofnumbers
Thanks, it works!