【问题标题】:put a http:// on a string if it does not contain it else disregard string in php如果它不包含它,则在字符串上放置一个 http:// 否则忽略 php 中的字符串
【发布时间】:2014-01-19 18:08:12
【问题描述】:

我正在尝试将 http:// 放在一个字符串上,如果它不包含它,然后忽略该字符串,如果它已经存在问题是它没有忽略字符串如果确实包含它,这是我的代码:

if(strpos($_POST['test-website'], "http://") === false || strpos($_POST['test-website'], "https://") === false){
    $url = "http://".$_POST['test-website'];
}else
    $url = $_POST['test-website'];

//Value: test.com
//Result: http://test.com

//Value: http://test.com
//Result: http://http://test.com

//Value: https://test.com
//Result: http://https://test.com

【问题讨论】:

  • strpos 返回一个数字或 false。从来都不是真的。
  • 无论这是一个错字,使用||而不是|(逻辑和按位运算)

标签: php string boolean href strpos


【解决方案1】:

strpos() 返回针存在的相对位置 haystack 字符串的开头(与偏移量无关)。退货 如果没有找到针,则为 FALSE。它不会返回 true。

if(strpos($_POST['test-website'], "http://") === false || strpos($_POST['test-website'], "https://") === false

【讨论】:

    【解决方案2】:

    您应该使用=== false 而不是!== truestrpos 永远不会返回true

    if(strpos($_POST['test-website'], "http://") === false || strpos($_POST['test-website'], "https://") === false) {
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 2017-02-07
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多