2017-10-12 38 views
1

我想將括號添加到字符串中的變量。我如何使用正則表達式在PHP上做到這一點?如何將括號添加到php的正則表達式模式的caputures?

字符串: UPDATE item_tbl SET name = '$name',code = '$code',category_fk = $category_fk,modified_by_fk = $modified_by_fk,price = $price

正則表達式: /\$(\w*)/g

輸出:

UPDATE item_tbl SET name = '($name)',code = '($code)',category_fk = ($category_fk),modified_by_fk = ($modified_by_fk),price = ($price)

回答

1

你可以試試這個:

(\$\w+) 

和替換由該:

($1) 

regex demo

樣品溶液(run here

$re = '/(\$\w+)/'; 
$str = 'UPDATE item_tbl SET name = \'$name\',code = \'$code\',category_fk = $category_fk,modified_by_fk = $modified_by_fk,price = $price'; 
$subst = '($1)'; 
$result = preg_replace($re, $subst, $str); 
echo $result; 

樣本輸出:

UPDATE item_tbl SET name = '($name)',code = '($code)',category_fk = ($category_fk),modified_by_fk = ($modified_by_fk),price = ($price)