2

我有一个变量要在 preg_match 中使用,并结合一些正则表达式:

$string = "cheese-123-asdf";
$find = "cheese";
if(preg_match("/$find-/d.*/", $string)) {
    echo "matched";
}

在我的模式中,我尝试使用奶酪进行匹配,然后是 - 和 1 位数字,然后是其他任何内容。

4

3 回答 3

4
  1. 更改/d\d
  2. 没有必要使用.*
  3. 如果您的字符串是由用户定义的(或可能包含一些字符(例如:/*...)),这可能会导致您的匹配出现问题。

代码:

<?php
$string = "cheese-123-asdf";
$find = "cheese";
if(preg_match("/$find-\d/", $string)) 
{
    echo "matched";
}
?>
于 2012-12-13T21:17:12.993 回答
3

/您输入错误\

if(preg_match("/$find-\d.*/", $string)) {

.*也不是真正必要的,因为模式将匹配任何一种方式。

于 2012-12-13T20:42:09.177 回答
1

对于数字,它是\d

if(preg_match("/$find-\d.*/", $string)) {
于 2012-12-13T20:42:13.390 回答