php - How to make multiple preg_match


How do I make multiplepreg_match on astring. I did a research and able to come out with below solutions.

$input = '@[email protected] & Good Day ~World~';
$regex = '/

$input_new = preg_replace($regex,'<i>$1</i>', $input);
echo $input_new;

the above will search for(~)string(~) and change to italic format. How do I want to make the search for(@)string(@) and change to bold format on the same text.




preg_replace, as the manual says, can also take more than one pattern and replacement:

$input = '@[email protected] & Good Day ~World~';
$regexes = array('/~(.*?)~/six',

$replaces = array('<i>$1</i>',

$input_new = preg_replace($regexes, $replaces, $input);
echo $input_new;



You do the same thing you did above, only this Time changing to and to like so. Otherwise, just create a Function to do that like so:


        function transposeBoldItalic($inputString, $embolden="Hello",$italicise="World"){
            $result = preg_replace("#(" . preg_quote($embolden)  . ")#", "<strong>$1</strong>", $inputString);
            $result = preg_replace("#(" . preg_quote($italicise) . ")#", "<em>$1</em>", $result);
            return $result;

        // TEST IT:
        $inputString = "Hello & Good Day World";

        var_dump(transposeBoldItalic($inputString, "Hello", "World"));
        echo(transposeBoldItalic($inputString, "Hello", "World"));

        // DUMPS 
        <strong>Hello</strong> & Good Day <em>World</em> 

Test it Here:




@osnapitzkindle answer is correct, but you can also use preg_replace_callback

echo preg_replace_callback('/([@~])(.*?)([@~])/', function ($matches){
    return (strpos($matches[1], '@') !== false) ? "<i>{$matches[2]}</i>" : "<b>{$matches[2]}</b>";}, $input

Ideone Demo

People are also looking for solutions to the problem: php - What kind of codes can be into PDO transactions?


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.