使用 strpos 改变变量内容

Using strpos to change variable content

如果变量的内容已存在于字符串中,我将尝试删除该变量的内容:

$baseurl = "http://mywebsite.ex/";
$b = $baseurl."http://";
$a = $b."http://mywebsite.ex";

if (strpos($a,$b) !== false) 
{
    echo 'true <br>';
    $baseurl = "";
    echo $a;
}

但是当我测试脚本时我得到:

true 
http://mywebsite.ex/http://http://mywebsite.ex

我预期的结果:

true 
http: //mywebsite.ex

我哪里错了?

使用 strpos() 时,您只能检测 $b 是否出现在 $a 中的某处,但不会将其删除。要删除它,您可以将 strpos() 的 return 值分配给一个变量,然后用 substr_replace()$a 中删除 $b,例如

if (($position = strpos($a,$b)) !== false) 
{
    echo 'true <br>';
    $baseurl = "";
    $a = substr_replace($a, "", $position, strlen($b));
    echo $a;
}

有了这个,您将删除 $a 中第一次出现的 $b。如果您想删除所有出现的事件,只需使用 str_replace(),例如

if (strpos($a,$b) !== false) 
{
    echo 'true <br>';
    $baseurl = "";
    $a = str_replace($b, "", $a);
    echo $a;
}

我不知道你想做什么,但我认为你有一些逻辑问题。

更新。 好的,现在我知道你想要什么了 ;),我想 @Rizier123:你做到了。

您在代码中所做的是:

strpos(): 你在这个 if ( strpos( $a, $b ) !== false ) 条件下问如果 $b ( http://mywebsite.ex/http:// ) is in $a ( http://mywebsite.ex/http://http://mywebsite.ex ) // 这总是正确的,因为你像 $a = $b . "http..... 一样连接字符串,所以 $b 总是在 $a

试试看输出:

$baseurl = "http://mywebsite.ex/";
$b = $baseurl . "http://"; // b looks like http://mywebsite.ex/http://
var_dump( $b );
$a = $b . "http://mywebsite.ex"; // a looks like http://mywebsite.ex/http://http://mywebsite.ex
var_dump( $a);


// strpos: you asking in this condition if $b ( http://mywebsite.ex/http:// ) is in $a ( http://mywebsite.ex/http://http://mywebsite.ex )
// this is always true because you concated the string like $a = $b . "http....., so $b is always in $a
if ( strpos( $a, $b ) !== false ) {
    echo 'true <br>';
    $baseurl = "";
    echo $a;
}