开发者

Regexp: how to match everythings that is not into a pattern?

开发者 https://www.devze.com 2023-01-02 01:04 出处:网络
I want to match everything in a string that does not match a given pattern; for example [a-z]. Given the string abc4jkf8 4à3in, I need to match 48 4à3.

I want to match everything in a string that does not match a given pattern; for example [a-z].

Given the string abc4jkf8 4à3in, I need to match 48 4à3.

I've tried with ([a-z])+(?![a-z]) but this matches exactly the opposite of what I need. With the string above, this regexp matches abcjkfin.

Any开发者_运维知识库 ideas?


You use a negative set:

([^a-z]+)


why not use preg_replace.

$string = "abc4jkf8 4à3in";
echo preg_replace("/[a-z]/", "", $string);

this gives the desired result


preg_match_all('/([^a-z]+)/si', $code, $result, PREG_PATTERN_ORDER);
$unmached = "";
for ($i = 0; $i < count($result[0]); $i++) {
    $unmached .= $result[0][$i];
}
echo $unmached;

[^a-z] matches every character that is not a-z.


You need to match any charater that is no alpha. The ^ tells not to match alpha chars

[^a-z]*


$a = "abc4jkf8 4à3in";

function stringConcat($a, $b) { return $a.$b; }

if (preg_match_all("/[^a-z]/", $a, $matches)) {
    echo array_reduce(reset($matches), 'stringConcat');
}

gives what you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消