acrobat
acrobat

Reputation: 2259

php preg_match_all not specific number

I want to exclude a specific number like 4800 from a string of numbers like 569048004801. I'm using php for this and the method preg_match_all some pattern's examples I have tried :

/([^4])([^8])([^0])([^0])/i
/([^4800])/i

Upvotes: 0

Views: 153

Answers (3)

Oussama Jilal
Oussama Jilal

Reputation: 7739

If you just want to see if a string contain 4800, you don't need regular expressions :

<?php

$string = '569048004801';

if(strpos($string,'4800') === false){
  echo '4800 was not found in the string';
}
else{
  echo '4800 was found in the string'; 
}

More information about strpos in the documentation here

Upvotes: 3

Andrew Cheong
Andrew Cheong

Reputation: 30273

/([^4])([^8])([^0])([^0])/i

This actually says, a sequence of four characters that is not "4800". Close.

/([^4800])/i

This actually says, a single character that is not '4', '8', or '0'.

Assuming you mean to capture a number that doesn't contain "4800" in it, I think you might want

/(?!\d*4800)\d+/i

This says, check first that we're not looking at a string of numbers with "4800" somewhere, and provided this is the case, capture the string of numbers. It's called a "negative lookahead assertion".

Upvotes: 1

Sean Bright
Sean Bright

Reputation: 120644

If you mean you simply want to remove 4800 from a string, this is easier with a str_replace:

$str = '569048004801';
$str = str_replace('4800', '', $str);

On the other hand, if you mean you want to know if a particular string of digits contains 4800, this will test that for you:

$str = '569048004801';

if (preg_match_all('/4800/', $str) > 0) {
    echo 'String contains 4800.';
} else {
    echo 'String does not contain 4800.';
}

Upvotes: 2

Related Questions