【问题标题】:Return substring in array with regex使用正则表达式返回数组中的子字符串
【发布时间】:2016-07-06 13:35:26
【问题描述】:

我有以下字符串,例如:'Hello [owner], we could not contact by phone [phone], it is correct?'

Regex 想以数组的形式返回,所有在[] 内。括号内只能是字母字符。

返回:

$array = [
  0 => '[owner]',
  1 => '[phone]'
];

我应该如何继续在 php 中返回这个?

【问题讨论】:

  • 你标记了这个问题preg-match-all——该函数的文档有有用的例子。你试过了吗?

标签: php regex preg-match preg-match-all


【解决方案1】:

试试:

$text = 'Hello [owner], we could not contact by phone [phone], it is correct?';
preg_match_all("/\[[^\]]*\]/", $text, $matches);
$result = $matches[0];
print_r($result);

输出:

Array
(
    [0] => [owner]
    [1] => [phone]
)

【讨论】:

    【解决方案2】:

    我假设所有这些的最终目标是您想用其他文本替换 [placeholder]s,所以请改用 preg_replace_callback

    <?php
    $str = 'Hello [owner], we could not contact by phone [phone], it is correct?';
    
    $fields = [
      'owner' => 'pedrosalpr',
      'phone' => '5556667777'
    ];
    
    $str = preg_replace_callback('/\[([^\]]+)\]/', function($matches) use ($fields) {
      if (isset($fields[$matches[1]])) {              
        return $fields[$matches[1]];                    
      }
      return $matches[0];              
    }, $str);        
    
    echo $str;
    ?>
    

    输出:

    您好 pedrosalpr,我们无法通过电话 5556667777 联系,是否正确?

    【讨论】:

      猜你喜欢
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 2018-07-23
      • 1970-01-01
      • 2018-11-09
      • 2013-11-04
      • 1970-01-01
      相关资源
      最近更新 更多