在PHP

时间:2018-10-26 11:07:05

标签: php

我有以下字符串:

  • Pizza'PizzaName',这是一定的披萨
  • Pizza'NamePizza',这是一定的披萨
  • “夏威夷”披萨这是一定的披萨
  • Pizza'Pepperoni'这是一定的披萨
  • 披萨是非常不错的披萨

因此,我希望包含(word)的字符串在该单词之后分割,但是如果字符串中没有(word),我不想分割。所以我这样做:

if(strpos($title, "'" !== false)

这将检查字符串是否包含'字符。但是现在我必须在第二个'处分割字符串。现在我尝试爆炸,但是这给了我数组中的多个变量。我希望有:

  1. 名称
  2. 子字符串

我该怎么做?有没有办法给explode一个变量,使其仅在第二个'字符之后拆分它?

编辑:对不起,这是我想要的结果:

  1. Pizza'PizzaName'->名称
  2. 这是一定的披萨-> SUBSTRING

  1. Pizza'NamePizza'
  2. 这是一定的披萨

  1. “夏威夷”比萨饼
  2. 这是一定的披萨

1 个答案:

答案 0 :(得分:3)

preg_split()仅在字符串中有两个单引号的情况下才拆分字符串(在两个所需的子字符串之间的空格处)。

[^']+     #match 1 or more non-single-quote characters
'         #match single quote
[^']+     #match 1 or more non-single-quote characters
'         #match single quote
\K        #forget previously matched characters and then match space

代码:(Demo)(Regex Demo

$strings = [
    "Pizza 'PizzaName' this is a certain pizza",
    "Pizza 'NamePizza' this is a certain pizza",
    "Pizza 'Hawaii' this is a certain pizza",
    "Pizza 'Pepperoni' this is a certain pizza",
    "Pizza is a very nice pizza"
];
foreach ($strings as $string) {
    print_r(preg_split("~[^']+'[^']+'\K ~", $string));
}

输出:

Array
(
    [0] => Pizza 'PizzaName'
    [1] => this is a certain pizza
)
Array
(
    [0] => Pizza 'NamePizza'
    [1] => this is a certain pizza
)
Array
(
    [0] => Pizza 'Hawaii'
    [1] => this is a certain pizza
)
Array
(
    [0] => Pizza 'Pepperoni'
    [1] => this is a certain pizza
)
Array
(
    [0] => Pizza is a very nice pizza
)

要查看100多个使用\Khere are some of my posts的出色功能的示例。