doudu22272099831
2015-11-23 10:00
浏览 163
已采纳

使用strpos更改变量内容

I'm trying to remove the contents of a variable if it already exists in a string:

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

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

But when I test the script I get:

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

I expected the result:

true 
http: //mywebsite.ex

Where am I wrong?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试删除变量的内容(如果它已经存在于字符串中): \ n

  $ baseurl =“http://mywebsite.ex/”; 
 $ b = $ baseurl。“http://”; 
 $ a = $ b。“http:/  /mywebsite.ex";
nnif(strpos($ a,$ b)!== false)
 {
 echo'true&lt; br&gt;'; 
 $ baseurl =“”; 
 echo $  a; 
} 
   
 
 

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

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

我期待结果:

 <  code> true 
http://mywebsite.ex
nn

我错在哪里?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongwen4487 2015-11-23 10:06
    已采纳

    I don't know what you are trying to do, but I think you have some logical problems.

    Update. OK now I know what you wanted ;), I think @Rizier123: you nailed it.

    What you do in you code is:

    strpos(): you are asking in this if ( strpos( $a, $b ) !== false ) 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

    Try this and take a look at the output:

    $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;
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duanquannan0593 2015-11-23 10:04

    With strpos() you only detect if $b occurs somewhere in $a, but it doesn't remove it. To remove it you can assign the return value of strpos() to a variable and then cut out $b from $a with substr_replace(), e.g.

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

    With this you will remove the first occurence of $b in $a. And if you would want to remove all occurences, just use str_replace(), e.g.

    if (strpos($a,$b) !== false) 
    {
        echo 'true <br>';
        $baseurl = "";
        $a = str_replace($b, "", $a);
        echo $a;
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题