Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find exact number or word using preg_match(), or another way

Tags:

regex

php

After a lot of time finding some examples around the web without success, i came here... So, i'm using this code to find exact word:

preg_match("/\b".$searched."\b/i", file_get_contents("mytextfile1.txt"))

This works fine with letters/characters, but when i use a nuber as 005, 087, 172 the IF condition return always FALSE... below, two examples:

Working examples:

$searched = "someword";
if ( preg_match("/\b".$searched."\b/i", file_get_contents("mytextfile1.txt")) ) {
// TRUE
}

NON working example:

$searched = "047";
if ( preg_match("/\b".$searched."\b/i", file_get_contents("mytextfile1.txt")) ) {
// FALSE
}

The .TXT file contain many strings like this:

somenametofind|alinktoimages_icon_047_00.png|some-text

Please, can you tell me what is wrong in that regex? And how can i solve it? I hope you are understand my problem... thanks a lot in advance. :)

like image 978
Devilix Avatar asked Dec 21 '25 19:12

Devilix


1 Answers

Your issue is that \b matches any non-word character i.e. [^A-Za-z0-9_]. Note that _ is considered to be a word character, so \b047\b will not match _047_. If you want to exclude _ from your "words", change your regex to

"/(^|[^A-Za-z0-9])$searched([^A-Za-z0-9]|$)/i"

Demo on 3v4l.org

If you want to allow words to include _, it might be simpler to change the boundaries when searching for numbers. For example:

$string = 'somenametofind|alinktoimages_icon_047_00.png|some-text';
$searched = array("some-text", "047");
foreach ($searched as $s) {
    $b = is_numeric($s) ? '\D' : '\b';
    if (preg_match("/$b$s$b/i", $string) ) {
        echo "found $s\n";
    }
}

Output:

found some-text
found 047

Demo on 3v4l.org

like image 56
Nick Avatar answered Dec 23 '25 09:12

Nick