vitto_primatti
vitto_primatti

Reputation: 57

Regex select anything but numbers containing 5

I need to exclude all numbers that contain 5 from a string using regex.

Given a string of integers separated by commas spaces i.e. "1 2 3 4 5 ... 15 16" i need to return this string with excluded numbers that contain 5 (5, 15, 54 etc.) using regex. I tried to achieve this by using negative lookahed with no luck. It successfully captures numbers which end with 5 (15, 75) but not the ones which start with it (56,57). Please help me figure out what i am missing.

$s = implode(' ', range($start, $end));
$sm = preg_replace('/(?!\d*5\d*)(\d+)\d*/', '', $s)

Upvotes: 1

Views: 72

Answers (3)

JackPRead
JackPRead

Reputation: 178

Use this pattern

\b(?:[0-4]|[6-9])+\b

It is quite simple. \b is a word boundary (this is short for (?:\w\W|\W\w)) and then it searches for digits 0-4 or 6-9.

Further explanation:
\b word boundary
(?: start non-capturing group
[0-4]|[6-9] match a character between 0-4 or 6-9 inclusively. i.e. any digit except 5
) end capture group
+ quantier to give 1 or more of the previous match which is the capture group
\b word boundary

edit: changed * to + as I can't imagine a reason why you'd want to match no digits

Upvotes: 2

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

You can use this regex to select a number that contains a 5 (optionally remove space after that too) within it and replace it with empty string,

-?\d*5\d* ?

Demo

Hence try changing your code to,

$s = "1 2 3 4 -5 8 7 15 7 22 51 15 16 -23532 215 232 522 952 332 -25 56 434";
$sm = preg_replace('/-?\d*5\d* ?/', '', $s);
echo $sm;

Prints,

1 2 3 4 8 7 7 22 16 232 332 434

Upvotes: 1

pr1nc3
pr1nc3

Reputation: 8338

<?php

$string = '1 2 3 6 5 55 12 14 75 61 8590';


$data = explode(' ',$string);


foreach($data as $row){
    if (strpos($row, '5') !== false) {
        $newArray[] = $row;
    }
}

echo '<pre>';
print_r($newArray);

Above code will accept a string seperated by coma, and after explode will put each of the values that contain '5' in a new array to be printed. Output is :

Array
(
    [0] => 5
    [1] => 55
    [2] => 75
    [3] => 8590
)

Upvotes: 1

Related Questions