2

is there a way in php to have a combined preg_match_all and preg_replace?

Having a string $string like:

Lorem Ipsum `code block` lorem `code`

I want to remove the code blocks from the string and keep $string (without the code blocks) but also keep an array of matches, like I would get with preg_mach_all.

[
  0 => `code block`,
  1 => `code`
]

Is this possible in one command in php?

1 Answer 1

1

You can use preg_replace_callback:

$s = 'Lorem Ipsum `code block` lorem `code`';

$matches = array(); // array to keep removed matches
$repl = preg_replace_callback('/(`[^`]*`)\h*/', function($m) use(&$matches) {
            $matches[]=$m[1]; return ''; }, $s);

echo $repl . "\n";
print_r($matches);

Output:

Lorem Ipsum lorem
Array
(
    [0] => `code block`
    [1] => `code`
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.