在PHP中拆分包含多个字符的字符串
I have the following 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
So I want the strings containing the (word)
to be split after this word, but i don't want to split if there is not (word)
in the string. So I do this:
if(strpos($title, "'" !== false)
This checks if the string contains the ' character. But now I have to split the string at the second '. Now I tried explode, but that gives me multiple variables in the array. I want there to be:
- name
- the substring
How can I do this? Is there a way to give the explode a variable to only split it after the second '
character?
EDIT: Sorry here is the result I want:
- Pizza 'PizzaName' -> NAME
- this is a certain pizza -> SUBSTRING
- Pizza 'NamePizza'
- this is a certain pizza
- Pizza 'Hawaii'
- this is a certain pizza
preg_split()
will ONLY split the string (on the space between the two desired substrings) if there are two single quotes in the string.
[^']+ #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
Code: (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));
}
Output:
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
)
To see over 100 more examples of using the awesomeness of \K
, here are some of my posts.