Question

I have text like this, "wow! It's Amazing.". I need to split this text by either "!" or "." operator and need to show the first element of array(example $text[0]).

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

here $text[0] having the value of "wow" only. but I want to know which string occurring first in text (whether its "!" or "."), so that I will append it to $text[0] and shown like this "wow!".

I want to use this preg_split in smarty templates.

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

the above code displays the result as "wow". There is no preg_match in smarty, so far i have searched.other wise,i would use that. Any help would be appreciated.Thanks in Advance.

Was it helpful?

Solution

Instead of preg_split you should use preg_match:

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

If you must use preg_split only then you can do:

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

OTHER TIPS

Try this

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

it will split the string in to two.

$1 => wow!

$2 => it's, a nice product.

see here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top