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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里