需要帮助理解 create_function() 和正则表达式
在对 SO 和其他论坛进行了大量搜索之后,我也绊倒了各种 php 函数文档,我尝试编辑我在这里找到的一个函数(将 URL 转换为可点击的链接),这样它也可以处理嵌入式视频,不幸的是我的技能很差并且我相信我不完全理解 create_function()
能否成功做到这一点。
所以这是我的炒鸡蛋代码:
private function _check4Links($text){
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
$callback = create_function('$matches', '
$url = array_shift($matches);
$url_parts = parse_url($url);
if(preg_match("%(?:youtube\.com/(?:user/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i", $url, $match)){
return sprintf(\'<iframe title="YouTube video player" class="youtube-player" type="text/html" width="400" height="244" src="http://www.youtube.com/embed/\'.$match[1].\'" frameborder="0" allowFullScreen></iframe>\', $url, $text);
}else{
$text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
$text = preg_replace("/^www./", "", $text);
$last = -(strlen(strrchr($text, "/"))) + 1;
if ($last < 0) {
$text = substr($text, 0, $last) . "…";
}
return sprintf(\'<a target="_blank"rel="nofollow" href="%s">%s</a>\', $url, $text);
}');
return preg_replace_callback($pattern, $callback, $text);
}
我还应该提到,我不正在寻找某人向我展示正确的代码,我正在寻找某人向我解释为什么我的代码不起作用以及我做错了什么。谢谢您的宝贵时间:)
After allot of searching around SO and other forums also stumbling over various php function documentation, I tried to edit a function that I found on here(converts URLs to clickable links) so it will also handle embedded video, unfortunately my skill set is poor and I believe I don't fully understand create_function()
to be successful at this.
So here's my scrambled egg code:
private function _check4Links($text){
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
$callback = create_function('$matches', '
$url = array_shift($matches);
$url_parts = parse_url($url);
if(preg_match("%(?:youtube\.com/(?:user/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i", $url, $match)){
return sprintf(\'<iframe title="YouTube video player" class="youtube-player" type="text/html" width="400" height="244" src="http://www.youtube.com/embed/\'.$match[1].\'" frameborder="0" allowFullScreen></iframe>\', $url, $text);
}else{
$text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
$text = preg_replace("/^www./", "", $text);
$last = -(strlen(strrchr($text, "/"))) + 1;
if ($last < 0) {
$text = substr($text, 0, $last) . "…";
}
return sprintf(\'<a target="_blank"rel="nofollow" href="%s">%s</a>\', $url, $text);
}');
return preg_replace_callback($pattern, $callback, $text);
}
I should also mention that i'm not looking for someone to just show me the correct code, I'm looking for someone to explain to me why my code is not working and what i am doing wrong. Thank you for your time :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个修复:
输出是:
Here is a fix:
The output is: