tags:

views:

75

answers:

5

Something like this,but I don't want to do it 2 times:

preg_match_all($pattern,$string,$matches);
$string = preg_replace($pattern,'',$string);
A: 

you mean something like this?

$string = preg_replace(preg_match_all($pattern,$string,$matches),'',$string);

Update:

I thought so you want something like this .. but you could see now that its not possible without complicating things (as @gnud answer). So answer is No, you can't do it in one line.

Wbdvlpr
won't work, preg_match_all returns an int not the matches.
James
Not work,but seems he gets what I mean.
Misier
So probably you got the answer now that its not possible to do it in one line. :)
Wbdvlpr
+1  A: 

OK,

so you want to capture the matches, and replace, in one function call. I'm guessing that you don't want to process a costly regex twice, otherwise I can see no good reason to want to make your code less readable.

Anyway,

you could try using preg_replace_callback(). Something like:

class MatchReplace {

    var $matches;
    var $pattern;
    var $replacement;
    var $string;
    var $matchCount;

    function __construct($pattern, $replacement) {
     $this->replacement = $replacement;
     $this->pattern = $pattern;
    }

    function matchAndReplace($string) {
     $this->string = $string;

     var_dump($string);
     var_dump($this->pattern);

     return preg_replace_callback($this->pattern, 
       array($this, '_worker'), $string, -1, $this->matchCount);
    }


    function _worker($matches) {
     echo "Matches:\n";
     var_dump($matches);
    }
}

Example run:

echo "<pre>\n";
$m = new MatchReplace('|(abc)|', '');
echo "\nResult: \n".$m->matchAndReplace('XXXabcYYY');

echo "\n</pre>";

Output:

string(9) "XXXabcYYY"
string(7) "|(abc)|"
Matches:
array(2) {
  [0]=>
  string(3) "abc"
  [1]=>
  string(3) "abc"
}

Result: 
XXXYYY
gnud
That's much too complicated,I would even prefer to it twice..
Misier
Unless your regex is crazy complicated, there is NO good reason to do this. Just run it twice: First match, then replace.
gnud
Regex like that is better run twice
andho
A: 

If you don't need fancy replacing rules (like regular expressions), you should always use str_replace() function instead of ereg_replace() or preg_replace().

http://uk.php.net/str%5Freplace

This will do all occurrences and only 1 command.

Lizard
A: 

By the looks of it you are doing 2 completely separate things.

preg_match_all($pattern,$string,$matches); // return all the matches
$string = preg_replace($pattern,'',$string); // replace all the matches in the string

So you aren't actually doing anything twice. Unless you are using $matches somewhere further down the line, the first line is irrelevant if you are going to do the preg_replace afterwords anyway.

James
A: 
preg_match_all($pattern1,$string,$matches);
$result = preg_grep($pattern2, $matches);
unigg