开发者

Php how to use Explode in a sentence

I am thinking a way to do this. I want to get some text in a sentence.

This is a sample of $item_title in database:

cat1 + sub1 of cat1 + test 1 of sub1 of cat1

All i want to do is get the sentence starting from first ' + '

In this case i want to have:

sub1 of cat1 + test 1 of sub1 of cat1

开发者_JS百科$pieces = explode(" + ", $item_title);
$idonotneed = $pieces[0]; // cat1 


$pieces = explode(" + ", $item_title, 2);

You can pass a third parameter, that represents the max amount of segments you'd like to receive.

$pieces[0] will the be the first segment; pieces[1] the rest.


$pieces = explode(' + ', $item_title);
array_shift($pieces);
$wanted = implode(' + ', $pieces);


preg_replace('/^.*?\+ /', '', $item_title);

It's basically removing anything from the start of the string up until a + and a space are encountered... If there is no + followed by a space, it will return the whole sentence

Breaking down the regular expression:

  • .*? Match any character (non greedy, will explain in a sec).
  • \+ / A plus sign, followed by a space (added the / closing delimiter here otherwise the space doesn't show up.

Without the ? to make the first part non greedy, it would match the last +.

If the regular expression doesn't match anything, then nothing is replaced and the whole string will be returned.


You can do this with strpos and substr as well.

$text = "cat1 + sub1 of cat1 + test 1 of sub1 of cat1";
$pos = strpos($text, '+');
echo substr($text, $pos+1);


No need for explode() or regular expressions.

$wanted = substr($item_title, strpos($item_title, '+') + 1);

Or:

$wanted = substr(strstr($item_title, '+'), 1);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜