2010-08-23 92 views
1

说我有一个这样的字符串:正则表达式和PHP

$string = 'The /*quick*/ brown /*fox*/ jumped over the lazy /*dog*/.'; 

如何使用正则表达式找到的/ * * /的出现和替换每个值,像这样:

/*quick*/ with the value of $_POST['quick'] 
/*fox*/ with the value of $_POST['fox'] 
/*dog*/ with the value of $_POST['dog'] 

我已使用此模式尝试使用preg_replace:~/\*(.+)\*/~e

但它似乎并没有为我工作。

回答

4

模式(.+)太贪婪。它会找到最长的匹配,即quick*/ brown /*fox*/ jumped over the lazy /*dog,所以它不会工作。

如果将没有*出现/**/之间,然后使用:

preg_replace('|/\*([^*]+)\*/|e', '$_POST["$1"]', $string) 

否则,使用惰性限定符:

preg_replace('|/\*(.+?)\*/|e', '$_POST["$1"]', $string) 

实施例:http://www.ideone.com/hVUNA

+0

'的preg_replace( '|/\ *([^ *] +)\ */| E', '$ _POST [ “$ 1”]',$字符串)'精美把 – RobertPitt 2010-08-23 15:31:34

+0

preg_replace('|/\ *([^ *] +)\ */| e','$ _POST [“$ 1”]',$ string)做得很好,谢谢。 – Mike 2010-08-23 15:39:28

0

可以概括这个(PHP 5.3+,动态功能):

$changes = array('quick' => $_POST['quick'], 
       'fox' => $_POST['fox'], 
       'dog' => $_POST['dog'] ); 

$string = 'The /*quick*/ brown /*fox*/ jumped over the lazy /*dog*/.'; 

echo preg_replace(
     array_map(function($v){return'{/\*\s*'.$v.'\s*\*/}';}, array_keys($changes)), 
     array_values($changes), 
     $string 
    ); 

,如果你想拥有精细控制什么获取替换。否则,KennyTM already solved this

问候

RBO