PHP preg_replace在没有字符串的地方插入一个字符串

时间:2019-01-11 19:19:05

标签: php regex

我有一个包含字符串的变量$ var。

示例:

$var = "one, two , three = ?, four = 'val', five  , six = 1, seven, eight = 'val' , nine";

我想用preg_replace()编辑$ var,使$ var看起来像这样:

"one = ?, two = ?, three = ?, four = 'val', five = ?, six = 1, seven = ?, eight = 'val', nine = ?"

我的意思是:如果该列没有分配的值,则将其设置为' = ?'并删除不必要的空格。

我尝试了以下正则表达式,但还没结束:

$sql['set'] = preg_replace("/(\w+)\s?,/", "$1 = ?,", $sql['set']);

我研究了解决方案,但我无法涵盖所有​​可能性。

4 个答案:

答案 0 :(得分:3)

此正则表达式将处理您在初始字符串中丢失的= ?

([a-zA-Z]+)\s*(?:(,)|$)

当用\1 = ?\2替换但为了在逗号前修剪多余的空格时,您需要将另一个正则表达式+,替换为,,因此您可以在php中使用此多替换代码,

$var = "one, two , three = ?, four = 'val', five  , six = 1, seven, eight = 'val' , nine";
echo preg_replace(['/([a-zA-Z]+)\s*(?:(,)|$)/i', '/ +,/i'], ['\1 = ?\2', ','], $var);

哪个会提供您想要的输出,

one = ?, two = ?, three = ?, four = 'val', five = ?, six = 1, seven = ?, eight = 'val', nine = ?

答案 1 :(得分:1)

确实快要到了。

  • 您只需要*作为空格的量词,而不是?

  • 理想情况下,请勿使用\w来匹配密钥,因为这也会意外地匹配= 1

  • 也许使用一些lookarounds来确保之前没有=

我会选择:

preg_replace("/ (?<= ^|,|,\s)  ([a-z]+)  (?=\s*(,|$)) /x", "$1 = ?", $var)
#                       ↑         ↑            ↑
#              preceding comma   key   following comma / end

前面的逗号匹配有点黑(只是寻找一个可选的空格),但是如果限制允许的键名,也是多余的。

答案 2 :(得分:1)

这是一个非正则表达式解决方案:

$var = "one, two , three = ?, four = 'val', five  , six = 1, seven, eight = 'val' , nine";
$arr = explode(',', $var);
foreach($arr as $i => $e)
{
    $arr[$i] = (strpos($e, '=') === false) ? trim($e).' = ?' : trim($e);
}

echo implode(', ', $arr);

答案 3 :(得分:0)

另一种解决方案是使用explodearray_map并使用preg_match检查该值是否与键=值模式不匹配。然后,如果没有,请在值中添加= ?

模式

\w+\h*=\h*\S

这将匹配

  • \w+\h*匹配1+个单词字符,后跟0+个水平空格
  • =字面上匹配
  • \h*\S匹配0+个水平空格,然后不匹配空白字符

例如

$var = "one, two , three = ?, four = 'val', five  , six = 1, seven, eight = 'val' , nine";

echo implode(', ', array_map(function($x){
    return preg_match('/\w+\h*=\h*\S/', $x) === 0 ? $x.' = ?' : $x;
}, array_map("trim", explode(',', $var))));

结果

one = ?, two = ?, three = ?, four = 'val', five = ?, six = 1, seven = ?, eight = 'val', nine = ?

Php demo

如果不使用正则表达式并且列名本身不能包含等号,则可以使用strpos来检查字符串是否包含=

$var = "one, two , three = ?, four = 'val', five  , six = 1, seven, eight = 'val' , nine";

echo implode(', ', array_map(function($x){
    return strpos($x, '=') === false ? $x.' = ?' : $x;
}, array_map("trim", explode(',', $var))));

Php demo