简体   繁体   English

PHP表达式preg_match

[英]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或2等等,然后执行我的逻辑,因为数字可能会改变之前是字符串,但是数字不能,我尝试使用

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. 假设一次恰好找到一个空格后跟字符串“ 1”但返回false,则返回true。

Maybe some of you have had more experience with regular expressions in php and can help me. 也许你们中的一些人在php中使用正则表达式有更多经验,可以为我提供帮助。

Thank you very much in advance. 提前非常感谢您。

You could use strpos instead of preg_match! 您可以使用strpos代替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: 或者,如果Number必须在字符串的末尾:

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

You forgot the regex delimiters. 您忘记了正则表达式分隔符。 Use preg_match('/ 1/', ...) instead. 请使用preg_match('/ 1/', ...)

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 . 参见Lars Ebert的答案

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. 我在描述1的3个单独的字符串值(即IsAnother 1和OneMore 1)上测试了上述正则表达式。每个表达式都被表达式确定为真,并保存到组1中。

The explanation of the regex code is: 正则表达式代码的解释是:
() Match the regular expression between the parentheses and capture the match into backreference number 1. ()匹配括号之间的正则表达式,并将匹配项捕获到反向引用编号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) \\ s匹配单个空格字符(空格,制表符,换行符)
[1] Match the character 1 [1]匹配字符1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM