douyou2234 2018-10-26 11:07
浏览 196
已采纳

在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:

  1. name
  2. 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:

  1. Pizza 'PizzaName' -> NAME
  2. this is a certain pizza -> SUBSTRING

  1. Pizza 'NamePizza'
  2. this is a certain pizza

  1. Pizza 'Hawaii'
  2. this is a certain pizza
  • 写回答

1条回答 默认 最新

  • dongweicha6077 2018-10-26 11:42
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败