首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP - If语句如果字符串与动态数字匹配

PHP - If语句如果字符串与动态数字匹配
EN

Stack Overflow用户
提问于 2018-04-26 10:53:39
回答 5查看 91关注 0票数 0

我有一个PHP字符串,如下所示

代码语言:javascript
复制
$string = 'This is day 7 of the task';

数字会根据那一周发生的事情而变化,所以我尝试做一个if语句来检查一个数字,设置如下

代码语言:javascript
复制
if ($string == 'This is day 7 of the task') {
    echo 'Task day is set to a number';
}

我现在想匹配它,不管数字是多少,我最好的方法是什么,regex?

可能是这样吧?

代码语言:javascript
复制
$string = 'This is day 7 of the task';
$isAMatch = preg_match("/This is day \(\d)+\ of the task\/", $string);
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2018-04-26 10:57:52

你确实可以这样做:

代码语言:javascript
复制
if (preg_match("/^This is day [0-9]+ of the task$/", $string)) {
    echo 'Task day is set to a number';
}

^的意思是“开始”,$的意思是“结束”。如果您的字符串可以在开头或结尾包含其他字符,则删除它们。

票数 3
EN

Stack Overflow用户

发布于 2018-04-26 11:06:17

您的实际正则表达式无法工作,因为您正在转义括号\(和最后一个分隔符\/。如果你不需要知道号码,你可以用:

代码语言:javascript
复制
$string = 'This is day 7 of the task';
$isAMatch = preg_match('~This is day \d+ of the task~', $string);

如果您想得到这个号码,可以添加一个捕获组:

代码语言:javascript
复制
$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
}
票数 1
EN

Stack Overflow用户

发布于 2018-04-26 11:08:06

正如您所说,可以使用regex来实现这一点:

代码语言:javascript
复制
<?php
$string = 'This is day 7 of the task';
preg_match('~[0-9]~', $string, $matches);
var_dump($matches);

输出:

代码语言:javascript
复制
array(1) {
[0]=>
    string(1) "7"
}

现在你可以跟著

代码语言:javascript
复制
if(count($matches) > 0) {
    echo $matches[0]; // 7
}

https://3v4l.org/aiVlV

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50041159

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档