如何在单词之间添加双引号并在单词之间添加空格?

时间:2016-12-16 06:25:36

标签: php regex preg-replace

鉴于以下字符串(是,STRING,而不是数组),我想在国家/地区名称周围添加双引号。

$string = "Array ( [0] => Array ( [nicename] => Afghanistan [phonecode] => 93 ) [1] => Array ( [nicename] => United States [phonecode] => 1 )";

我想要以下字符串:

Array ( [0] => Array ( [nicename] => "Afghanistan" [phonecode] => 93 ) [1] => Array ( [nicename] => "United States" [phonecode] => 1 )

我该怎么做?

注意: 此字符串仅显示两个国家/地区,但实际数据将包含一百多个国家/地区。

我在考虑做类似

的事情
$string = preg_replace("/[[:alpha:]]/", "/\"[[:alpha:]]\"/", $string);

但问题是,对于第二个参数,(1)PHP如何知道该字符类[[:alpha:]]是什么,以及(2)除了字母字符外,国家/地区的名称可能还包含空格。

2 个答案:

答案 0 :(得分:1)

您应该在构建数组的情况下执行此操作,但可以使用正则表达式完成...

您需要在nicename之后捕获所有内容,直到[)(例如,如果nicename位于"数组"的最后或中间)。

使用类似的东西:

(\[nicename\] => )([^\[)]+)

应该完成,然后你需要引用找到的国家名称:

$1"$2" 

演示:https://regex101.com/r/7TeUQu/1

这个国家名称后面有额外的空格,因为那里允许有空格。在PHP中,我们需要使用preg_replace_callback和trim函数来解决这个问题。

$regex = '/(\[nicename\] => )([^\[)]+)/';
$replace = '$1"$2" ';
$string = 'Array ( [0] => Array ( [nicename] => Afghanistan [phonecode] => 93 ) [1] => Array ( [nicename] => United States [phonecode] => 1 )';
$string = preg_replace_callback($regex, function($match) {
     return $match[1] . '"' . trim($match[2]) . '" ';
}, $string);
echo $string;

PHP演示:https://eval.in/699678

答案 1 :(得分:0)

你走了:

$string = preg_replace('/(\[nicename\] =>) ([a-zA-Z ]+) \[/', '$1 "$2" [', $string);