PHP Preg_match match exact word
Asked Answered
A

4

5

I have stored as |1|7|11| I need to use preg_match to check |7| is there or |11| is there etc, How do I do this?

Actualize answered 29/11, 2010 at 15:18 Comment(0)
Q
2

Use the faster strpos if you only need to check for the existence of two numbers.

if(strpos($mystring, '|7|') !== FALSE AND strpos($mystring, '|11|') !== FALSE)
{
    // Found them
}

Or using slower regex to capture the number

preg_match('/\|(7|11)\|/', $mystring, $match);

Use regexpal to test regexes for free.

Quartermaster answered 29/11, 2010 at 15:19 Comment(0)
T
30

Use \b before and after the expression to match it as a whole word only:

$str1 = 'foo bar';       // has matches (foo, bar)
$str2 = 'barman foobar'; // no matches

$test1 = preg_match('/\b(foo|bar)\b/', $str1);
$test2 = preg_match('/\b(foo|bar)\b/', $str2);

var_dump($test1); // 1
var_dump($test2); // 0

So in your example, it would be:

$str1 = '|1|77|111|';  // has matches (1)
$str2 = '|01|77|111|'; // no matches

$test1 = preg_match('/\b(1|7|11)\b/', $str1);
$test2 = preg_match('/\b(1|7|11)\b/', $str2);

var_dump($test1); // 1
var_dump($test2); // 0
Tumular answered 29/11, 2010 at 16:0 Comment(0)
Q
2

Use the faster strpos if you only need to check for the existence of two numbers.

if(strpos($mystring, '|7|') !== FALSE AND strpos($mystring, '|11|') !== FALSE)
{
    // Found them
}

Or using slower regex to capture the number

preg_match('/\|(7|11)\|/', $mystring, $match);

Use regexpal to test regexes for free.

Quartermaster answered 29/11, 2010 at 15:19 Comment(0)
K
0

If you really want to use preg_match (even though I recommend strpos, like on Xeoncross' answer), use this:

if (preg_match('/\|(7|11)\|/', $string))
{
    //found
}
Kell answered 29/11, 2010 at 15:23 Comment(1)
To be clear, you can replace (7|11) for (7|11|13), for example, to match a 7, 11, or 13.Kell
M
0

Assuming your string always starts and ends with an | :

strpos($string, '|'.$number.'|'));
Malversation answered 29/11, 2010 at 15:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.