Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 重构:简单正则表达式_Php_Regex - Fatal编程技术网

Php 重构:简单正则表达式

Php 重构:简单正则表达式,php,regex,Php,Regex,Lets说我有以下内容:$string='New+York NY,其中+是我想要的\s,其中-是我想要的,'。格式化的字符串将显示为纽约州纽约市 这是我的密码: $string='纽约+纽约' $formattedLocation = preg_replace('/[+]/', ' ', $location); $formattedLocation = preg_replace('/-/', ', ', $formattedLocation); echo $format

Lets说我有以下内容:
$string='New+York NY
,其中
+
是我想要的
\s
,其中
-
是我想要的
,'
。格式化的字符串将显示为纽约州纽约市

这是我的密码: $string='纽约+纽约'

    $formattedLocation = preg_replace('/[+]/', ' ', $location);
    $formattedLocation = preg_replace('/-/', ', ', $formattedLocation);

    echo $formattedLocation;
这个代码有效。然而,它是丑陋的,我想重构它(如果可能的话)。我试过:

    $formattedLocation = preg_replace('/[+]/', ' ', $location) && preg_replace('/-/', ', ', $location);
然而,这不起作用,而且仍然是丑陋的。我应该使用不同的函数吗?或者我的正则表达式应该有所不同?请不要建议将其包装在自定义函数中(这不是我想要的答案)


谢谢你做了这么简单的事情你真的需要使用正则表达式吗?尝试使用:


为什么你认为你的初始代码很丑陋?只要你使用regexp,它是可读的,并且不会变得更有效。对于这种文字替换,你不需要使用preg_替换,只使用str_替换,这会更快。我认为它很难看,因为它是重复的。我想在不牺牲简单性的情况下缩短它。(如果可能的话)将替换件包裹在功能内-这是确保干燥的常用方法。或者干脆不使用preg_repalce,见@p.s.w.g的答案。@fabio很高兴我能帮上忙。快乐编码:)
$formattedLocation = str_replace(array('+', '-'), array(' ', ', '), $location);