【问题标题】:extract specific string with PHP使用 PHP 提取特定字符串
【发布时间】:2011-10-05 09:32:57
【问题描述】:

假设我们有这 4 个字符串:

  1. string1 = "Hello my name is 'George' and im fine";
  2. string2 = "Hello my name is 'Mary' and im fine";
  3. string3 = "Hello my name is 'Peter' and im fime";
  4. string4 = "Hello my name is 'Kate' and im fine";

我们如何只提取字符串中包含 '' 中的名称的部分?

提前致谢!

【问题讨论】:

    标签: php string extract


    【解决方案1】:

    你应该使用正则表达式:

    preg_match("/'(.+?)'/", $string, $matches);
    print_r($matches);
    

    http://php.net/preg_matchhttp://lt.php.net/preg_match_all 上查看更多信息

    【讨论】:

    • 我相信你需要转义单引号。
    【解决方案2】:
    $pieces = explode("'", $string);
    echo $pieces[1];
    

    【讨论】:

      【解决方案3】:

      在特定情况下,您可以使用 explode 函数根据分隔符将字符串拆分为数组,撇号将用于分隔字符串,以便以下代码产生您的答案:

      $tokens= explode("'", "Hello my name is 'Kate' and im fine");
      //The value you require is now found in $tokens[1];
      echo $tockens[1];
      

      或者,您可以使用 preg_match 存储与正则表达式中特定组的正则表达式匹配:

      $pattern = "Hello my name is '(.*)' and im fine";
      preg_match ($pattern ,  "Hello my name is 'Kate' and im fine", $matches)
      //The value you require is now found in $matches[1];
      echo $matches[1];
      

      【讨论】:

      • 我有这个:$string1 = "我的名字是'Kate',我很好"; $pattern = "我的名字是 '(.*)' 我很好"; preg_match($pattern, $string1, $matches); //你需要的值现在在 $matches[1];但它返回给我这个错误: 警告:preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash echo $matches[1];
      【解决方案4】:
      $string1 = "Hello my name is 'George' and im fine";
      preg_match_all("/\'(.*)\'/",$string1,$matches,PREG_SET_ORDER);
      echo $matches[0][1];
      

      上面将匹配单引号之间任意长度的字符串。如果您希望匹配单个单词,用单引号 '\w+' 代替 '.*' 也可以。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-07
        • 1970-01-01
        • 2021-11-08
        • 1970-01-01
        相关资源
        最近更新 更多