2011-09-29 38 views
0

我正在做一个链接和文本服务,但我有一个问题,那就是:只有1个输入文本形式,用户可以贴上这样的事情: http:// asdf .com - 这将登记为纽带,或者因为HTTP的“asdf http:// test .com”://,它会注册为网址,或 asdf - 这将注册为一个字符串,因为它不包含HTTP://确定URL或字符串PHP

,但我的当用户写入如下内容时会出现问题: asdf http://asdf.com,它在我当前的程序中输出“url”值。我已经经历过了大约一个小时,现在,我已经有了一个代码3位(!他们都被评论在同一文件中,所以请原谅我,如果他们放弃错误)

<? 
    $str = $_POST['paste']; 
    if(stristr($str, "http://")) { 
     $type = "url"; 
    } 
    if(stristr($str, "https://")) { 
     $type = "url"; 
    } 
    if($type!="url") { 
     $type = "string"; 
    } 
    ?> 

下一页:

<? 
    $type = "url"; 
     if($type=="url"){ 
     $t = substr($str, 8); 
     if(stristr($t, "https://")==$t){ 
     $type = "url";} 
     if(stristr($t, "https://")==$t){ 
     $type = "url";} 
     if(stristr($t, "http://")!=$t){ 
     $type = "string";} 
     if(stristr($t, "https://")!=$t){ 
     $type = "string";} 
     } 
     echo $type; 
     ?> 

下一页:

<?  
$url = "hasttp://cake.com"; 
    if(stristr($url, "http://")=="") { 
    $type = "string"; } else { 
    $type = "url"; 
    $sus = 1;} 
    if(stristr($url, "http://")==$url) { 
    $type = "url"; } 
    if($sus==1) { 
    $r = substr($url, 7); 
    if(stristr($r,"http://")!="http://") { 
    $type = "url"; } 
    if($r=="") { 
    $type = "string"; 
    } 
    } 
    echo $type; 
?> 

我不知道我怎么会去一个字符串进行分类,如“asdf http://asdf.com”作为一个字符串,而分类“asdf”作为一个字符串,并分类“http://asdf.com'作为网址..我还没有尝试过的另一个想法是strpos,但这就是我现在正在处理的内容。

任何想法?

非常感谢! :)

这个问题的某些部分由于某种原因而被切断,致歉!

+0

你基本上是问这些:http://stackoverflow.com/search?q=linkify+php?对? – Gordon

回答

4
$type = ''; 
if (preg_match('%^https?://[^\s]+$%', $url)) { 
    $type = 'url'; 
} else { 
    $type = 'string'; 
} 

这将匹配与http://https://启动时,并且在它不包含任何空间url类型的任何值。如果该值不是以http://https://开头,或者其中包含空格,则它将是类型string

+0

谢谢你!完美的作品! :) – Karan

+0

为什么不直接使用:$ type = preg_match('%^ https?:// [^ \ s] + $%',$ url))? 'url':'string'; –

+2

@AronCederholm因为我不想用三元运算符来吓唬OP。你当然可以这样做。 – Shef

0

如果我正确理解问题,您希望检测用户何时输入字符串和URL并相应地解析它们中的每一个。

尝试使用explode(" ", $userInput);,这将返回一个数组,其中包含由空格分隔的所有字符串。你可以检查数组中的每个元素并设置类型。

+0

哈哈,那实际上并不是我的问题,但我想你只是解决了它!谢谢你的伟大答案。对不起,我的问题在于将错误的标签贴在自己身上:\ – Karan

0

您应该使用正则表达式来检查,如果字符串以http

if(preg_match('/^http/',$string_to_check)){ //this is a url }

0
$type = strpos($str, 'http') === 0 ? 'url' : 'string': 

对strpos函数返回匹配的位置在字符串中或FALSE如果没有比赛开始。 tripple等于检查结果不仅转化为0(如FALSE所做的那样),而且它实际上也是整数(即字符串以http开头)。

您也可以使用类似

switch (true) { 
    case strpos(trim($str), 'http://') === 0: 
    case strpos(trim($str), 'https://') === 0: 
     $type = 'url'; 
     break; 
    default: 
     $type = 'string'; 
     break; // I know this is not needed, but it is pretty :-) 
} 
1

PHP parse_url是你的函数:

在严重畸形的URL,parse_url()可能会返回FALSE。如果省略组件参数,则返回关联数组。阵列中至少有一个元素存在。此阵列中的潜在密钥为:

  • 方案 - 例如, HTTP
  • 主机
  • 端口
  • 用户
  • 路径
  • 查询 - 问号后面?
  • 片段 - 的hashmark#

如果指定了组件参数,parse_url()之后返回,而不是阵列中的字符串(或整数,在PHP_URL_PORT的情况下)。如果请求的组件不存在于给定的URL中,则将返回NULL。