将字符串拆分为文本部分和URL部分

时间:2015-04-11 06:31:29

标签: php string

我正在开发社交网站,用户可以在其中发布带或不带文字的链接。如果用户发布了这样的链接:

downloaded image from www.google.com

我希望将此downloaded image from发布为简单文本,将www.google.com发布为标记。我已使用explode函数完成此操作:

$desc_res = explode("www.", $desc);
$post_desc = str_replace("https://", "", $desc_res[1]);
$description = $desc_res[0]."<a target=_blank href=".'http://'.$post_desc.">".$post_desc."</a>";

工作正常。我的问题是,如果没有wwwhttp的用户发帖,如何做同样的事情:

downloaded image from google.com

我尝试了很多解决方案,但没有任何帮助。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

 <?php
    echo strrchr("Hello world!","world");
    ?>
    o/p: world!

答案 1 :(得分:0)

尝试 -

if (strpos('www', $str) !== false) {
    // your code
}

答案 2 :(得分:-1)

我是通过使用正则表达式模式匹配自己完成的。如果用户将任何内容作为带有文本或链接的帖子,它将给出结果。以下是我的代码。

$reg_exUrl = "/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$text = "http://www.google.com The text you want to google.com filter goes here. google.com";
preg_match_all($reg_exUrl, $text, $matches);
$usedPatterns = array();
foreach($matches[0] as $pattern){
  if(!array_key_exists($pattern, $usedPatterns)){
    $usedPatterns[$pattern]=true;
    $text = str_replace($pattern, "<a href=http://$pattern>$pattern</a>", $text);   
  }
}
echo $text; 

输出应为:

http://www.google.com/ The text you want to google.com filter goes here google.com