我在网上找到了 curl parser 的这个想法,我想进一步开发它。原始解析器是为传递 youtube 而设计的。
class curly
{
/**
* Replace the macros in an input string
* @param string $input
* @return string
*/
public function replace ($input) {
//return preg_replace("/\{{2}([a-z]+\|.+)\}{2}/Ue",'$this->_replace("\\1")',$input); // original
return preg_replace("/\{{2}(([a-z]+\|.+)|([a-z\_]))\}{2}/Ue",'$this->_replace("\\1")',$input);
}
/**
* Run the replacement code on a given macro string
* @param string $input
* @return string
*/
private function _replace ($input) {
print_r($input);
list ($name,$params) = explode("|",$input);
if (method_exists($this,$name)) {
return $this->$name($params);
}else{
if($input === 'email_compnay') return 'company@example.com';
else if($input === 'email_personal') return 'personla@example.com';
}
throw new Exception ("Unrecognised macro: {$name}.",500);
}
/**
* Replaces a YouTube curly
* @param string $params
* @return string
*/
private function youtube ($params) {
parse_str($params);
// set defaults
if (!isset($id)) { $id = "ykwqXuMPsoc"; }
if (!isset($width)) { $width = 560; }
if (!isset($height)) { $height = 315; }
// output the final HTML
return "<iframe width=\"{$width}\" height=\"{$height}\" src=\"http://www.youtube.com/embed/{$id}\" frameborder=\"0\" allowfullscreen></iframe>";
}
}
有效的示例用法,
$curly = new curly();
$input = '<p>{{youtube|id=ykwqXuMPsoc&width=560&height=315}}</p>';
echo $curly->replace($input);
// return <p><iframe width="560" height="315" src="http://www.youtube.com/embed/ykwqXuMPsoc" frameborder="0" allowfullscreen></iframe></p>
另一个不起作用的例子,
$input = '<p>{{email_company}}</p>';
echo $curly->replace($input);
// return <p>{{email_company}}</p>
到时{{email_company}}
它应该返回company@example.com
,但它给了我
{{email_company}}
...
这个正则表达式有什么不对吗?
"/\{{2}(([a-z]+\|.+)|([a-z\_]))\}{2}/Ue"