デリエゴくん
デリエゴくん

Reputation: 1

php expressions preg_match

I have been trying to figure this out really hard and I cannot came out with a solution , I have an arrary of strings which is

"Descripcion 1","Description 2"

and I need to filter by numbers, so I thought maybe I can use preg_match() and find when there is exactly 1 number 1 or two or etc, and do my logic, becouse the string before the number may change, but the number cannot, I have tried using

preg_match(" 1{1}","Description 1") 

which is suppossed to return true when finds an space followed by the string "1" exactly one time but returns false.

Maybe some of you have had more experience with regular expressions in php and can help me.

Thank you very much in advance.

Upvotes: 0

Views: 67

Answers (3)

Lars Ebert-Harlaar
Lars Ebert-Harlaar

Reputation: 3537

You could use strpos instead of preg_match!

foreach($array as $string) {
    if(strpos($string, ' 1') !== false) {
        //String contains " 1"!!
    }
}

This would be much faster then a regular expression. Or, if the Number has to be at the end of the string:

foreach($array as $string) {
    if(substr($string, -2) == ' 1') {
        //String ends with " 1"!!
    }
}

Upvotes: 2

Steve Kinzey
Steve Kinzey

Reputation: 371

You might have success using

    if (preg_match('/(.*\s[1])/', $var, $array)) {
      $descrip = $array[1];
    } else {
      $descrip = "";
    }

I tested the above regex on the 3 separate string values of descripcion 1, thisIsAnother 1, andOneMore 1. Each were found to be true by the expression and were saved into group 1.

The explanation of the regex code is:
() Match the regular expression between the parentheses and capture the match into backreference number 1.
.* Match any single character that is not a line break character between zero and as many times possible (greedy)
\s Match a single whitespace character (space, tab, line break)
[1] Match the character 1

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318488

You forgot the regex delimiters. Use preg_match('/ 1/', ...) instead.

However, you do not need a regex at all if you just want to test if a string is contained within another string! See Lars Ebert's answer.

Upvotes: 1

Related Questions