用PHP是否可以检查句子是否具有特定结构?

时间:2019-10-07 06:35:33

标签: php preg-match

我查询了它的30 KG in G,问题是每个用户更改了数字(30),我想检查结构number KG in G中的句子,如果是-向我返回数字。 我尝试从中学习-link,但我不太了解如何将其更改为我的设计者。我需要一个解释,而不是代码。谢谢

3 个答案:

答案 0 :(得分:0)

使用preg_match

$input = "30 KG in G";
if (preg_match("/\b(\d+) KG in G\b/", $input, $matches)) {
    echo "MATCH: " . $matches[1]
}
else {
    echo "NO MATCH";
}

此打印:

MATCH: 30

以下是正则表达式模式的说明:

(\d+)       match AND capture any number
 KG in G    followed by ' KG in G'

在调用(\d+)之后,我们可以在$matches[1]中使用正则表达式模式捕获的数量preg_replace

答案 1 :(得分:0)

strpos()函数: strpos()函数用于查找字符串中子字符串的首次出现。如果存在子字符串,则该函数返回子字符串的起始索引,否则,如果在字符串中未找到子字符串,则返回False。

$str = '30 KG in G'; 

// Search substring  
$key = 'KG in G'; 

if (strpos($str, $key) == true) {  
    $domain = explode($key,$str);
    echo $domain[0]; 
}

答案 2 :(得分:0)

1种方法是使用Tim提到的正则表达式完成

另一种方法是快速破解,检查字符串是否包含必需的字符并通过拆分单词来获取数字。

$word = "30 KG in G";
$numbers = array();
if (strpos($word , ' KG in G') !== false) { // if string contains
      $numbers = explode($word," "); // split with space
}

在第一个索引上获取项目

if(!empty($numbers)){
echo  $numbers[0]; // has the required number
}