我有以下字符串:
因此,我希望包含(word)
的字符串在该单词之后分割,但是如果字符串中没有(word)
,我不想分割。所以我这样做:
if(strpos($title, "'" !== false)
这将检查字符串是否包含'字符。但是现在我必须在第二个'处分割字符串。现在我尝试爆炸,但是这给了我数组中的多个变量。我希望有:
我该怎么做?有没有办法给explode一个变量,使其仅在第二个'
字符之后拆分它?
编辑:对不起,这是我想要的结果:
答案 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多个使用\K
,here are some of my posts的出色功能的示例。