Strae
Strae

Reputation: 19445

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

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?

Upvotes: 2

Views: 197

Answers (5)

Spidfire
Spidfire

Reputation: 5523

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.

Upvotes: 2

Anthony
Anthony

Reputation: 107

why not use preg_replace.

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

this gives the desired result

Upvotes: 2

Artefacto
Artefacto

Reputation: 97835

$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.

Upvotes: 1

skyfoot
skyfoot

Reputation: 20769

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

[^a-z]*

Upvotes: 1

Guffa
Guffa

Reputation: 700342

You use a negative set:

([^a-z]+)

Upvotes: 7

Related Questions