PHP获取字符串中的特定单词

时间:2018-07-17 08:14:03

标签: php

我有一个网址。我想解析网址。我不想获得最后两个值。我该怎么办?

$str="first-second-11.1268955-15.542383564";

如我所愿

$str="first-second";

我使用了这段代码。但是我不想从上一个值中获得-

$arr = explode("-", $str);
for ($a = 0; $a < count($arr) - 2; $a++) {                
    $reqPage .= $arr[$a] . "-";       
}

3 个答案:

答案 0 :(得分:2)

您也可以使用正则表达式。这些是用于匹配字符串中字符组合的模式。

W*((?i)first-second(?-i))\W*

答案 1 :(得分:1)

使用explode()的第三个参数,称为limit

$str="first-second-11.1268955-15.542383564";
$arr = explode("-", $str, -2);
$reqPage = implode($arr, "-"); // contains "first-second"

答案 2 :(得分:0)

正则表达式是用于字符串操作的最快方法。试试这个。

$str="first-second-11.1268955-15.542383564";
preg_match('/^[a-z]*-{1}[a-z]*/i', $str, $matches);
$match = count($matches) > 0 ? $matches[0] : '';

echo $match;