【发布时间】:2013-08-19 08:28:48
【问题描述】:
我在网上发现了 curly 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"
【问题讨论】:
-
很抱歉,您到底想做什么。我不知道 PHP,但如果我知道你想要达到什么目的,我也许可以帮助你使用正则表达式?
-
谢谢。我想我需要一个能够从双花括号中获取
email_company或youtube|id=ykwqXuMPsoc&width=560&height=315的正则表达式。有可能吗? -
当前正则表达式只抓取
youtube|id=ykwqXuMPsoc&width=560&height=315,但不抓取email_company... -
修饰符列表中是小写的
u还是大写的U? -
它是原始代码的大写。
标签: php regex preg-replace php-5.4