我有一个PHP字符串,如下所示
$string = 'This is day 7 of the task';数字会根据那一周发生的事情而变化,所以我尝试做一个if语句来检查一个数字,设置如下
if ($string == 'This is day 7 of the task') {
echo 'Task day is set to a number';
}我现在想匹配它,不管数字是多少,我最好的方法是什么,regex?
可能是这样吧?
$string = 'This is day 7 of the task';
$isAMatch = preg_match("/This is day \(\d)+\ of the task\/", $string);发布于 2018-04-26 10:57:52
你确实可以这样做:
if (preg_match("/^This is day [0-9]+ of the task$/", $string)) {
echo 'Task day is set to a number';
}^的意思是“开始”,$的意思是“结束”。如果您的字符串可以在开头或结尾包含其他字符,则删除它们。
发布于 2018-04-26 11:06:17
您的实际正则表达式无法工作,因为您正在转义括号\(和最后一个分隔符\/。如果你不需要知道号码,你可以用:
$string = 'This is day 7 of the task';
$isAMatch = preg_match('~This is day \d+ of the task~', $string);如果您想得到这个号码,可以添加一个捕获组:
$string = 'This is day 7 of the task';
$isAMatch = preg_match('~This is day (\d*) of the task~', $string, $matches);
if ($isAMatch) {
echo $matches[1]; // 7
}发布于 2018-04-26 11:08:06
正如您所说,可以使用regex来实现这一点:
<?php
$string = 'This is day 7 of the task';
preg_match('~[0-9]~', $string, $matches);
var_dump($matches);输出:
array(1) {
[0]=>
string(1) "7"
}现在你可以跟著
if(count($matches) > 0) {
echo $matches[0]; // 7
}https://stackoverflow.com/questions/50041159
复制相似问题