Something like this,but I don't want to do it 2 times:
preg_match_all($pattern,$string,$matches);
$string = preg_replace($pattern,'',$string);
Something like this,but I don't want to do it 2 times:
preg_match_all($pattern,$string,$matches);
$string = preg_replace($pattern,'',$string);
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.
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
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.
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.
preg_match_all($pattern1,$string,$matches);
$result = preg_grep($pattern2, $matches);