user3174311
user3174311

Reputation: 1983

php: how to match multiple chars in a string using regex

given that string

$opStr = "1 + 2 - 3 * 4 / 5";
preg_match('/[\+\-\*\/]/', $strOp, $matches);

$matches is

array (size=1)
    0 => string '+' (length=1)

basically it is matching the first operand, is there a way to know if the string contains more operand, like in this example?

thanks

expected outputs

case "1 + 1": $matches[0] = '+'
case "2 - 1": $matches[0] = '-'
case "1 + 2 - 3 * 4 / 5": $matches[0] = '+-+/'
or
case "1 + 2 - 3 * 4 / 5": $matches[0] = array('+', '-', '+', '/')

Upvotes: 0

Views: 170

Answers (2)

engine9pw
engine9pw

Reputation: 364

Just use preg_match_all instead of preg_match.

<?php

$opStr = "1 + 2 - 3 * 4 / 5";
preg_match_all('/[\+\-\*\/]/', $opStr, $matches);

echo '<pre>';print_r($matches);echo '</pre>';

## will produce:
/*
Array
(
    [0] => Array
    (
        [0] => +
        [1] => -
        [2] => *
        [3] => /
    )
)
*/

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

You need to use preg_match_all function in-order to do a global match.

preg_match_all('~[-+*/]~', $strOp, $matches);

DEMO

$re = "~[-+*/]~m";
$str = "1 + 2 - 3 * 4 / 5";
preg_match_all($re, $str, $matches);
print_r($matches);

Output:

Array
(
    [0] => Array
        (
            [0] => +
            [1] => -
            [2] => *
            [3] => /
        )

)

Upvotes: 1

Related Questions