如何在多个字符串中查找文本中首先出现的字符串?

时间:2014-02-20 05:28:25

标签: php regex preg-match smarty preg-split

我有这样的文字,“哇!太棒了。”我需要用“!”分割这个文本。要么 ”。”运算符并需要显示数组的第一个元素(例如$ text [0])。

$str="wow! it's, a nice product.";
$text= preg_split('/[!.]+/', $str); 

这里$ text [0]只有“哇”的值。但我想知道哪个字符串首先出现在文本中(无论是“!”还是“。”),以便我将它附加到$ text [0]并显示为“哇!”。

我想在smarty模板中使用这个preg_split。

<p>{assign var="desc" value='/[!.]+/'|preg_split:'wow! it's, a nice product.'}
{$desc[0]}.</p>

上面的代码将结果显示为“哇”。智能没有preg_match,到目前为止我已经搜索过了。其他明智的,我会用它。 任何帮助将不胜感激。谢谢你。

2 个答案:

答案 0 :(得分:2)

而不是preg_split,您应该使用preg_match

$str="wow! it's, a nice product.";
if ( preg_match('/^[^!.]+[!.]/', $str, $m) )
   $s = $m[0]; //=> wow!

如果您必须使用preg_split,则可以执行以下操作:

$arr = preg_split('/([^!.]+[!.])/', $str, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
   $s = $arr[0]; //=> wow!

答案 1 :(得分:1)

试试这个

 /(.+[!.])(.+)/

它会将字符串拆分为两个。

$ 1 =&gt;哇!

$ 2 =&gt;这是一个不错的产品。

see here