2016-11-15 50 views
0

我看到它,并不确定它是在JS还是PHP,但如果它可能在PHP中,这将是伟大的!如果没有,如果没有一个IF,我将如何去解决它,如果没有一个,那么我该如何去解决它?在PHP变量中做一个OR?

代码:

$myvar = str_replace("hello","jpg",$myvar) || str_replace("hello","gif",$myvar); //Didnt work 

,我尝试:

$myvar = (str_replace("hello","jpg",$myvar) || str_replace("hello","gif",$myvar)); //Didnt work 

基本上是我想在这里实现是运行回来真的不管一个人。 如果它不能做:str_replace("hello","jpg",$myvar)然后做str_replace("hi","gif",$myvar)。现在我试图做一个IF,但也没有工作。

我IF也没有工作:

if (str_replace("hello","jpg",$myvar) == true) 
{ 
    $myvar = str_replace("hello","jpg",$myvar); 
} 
else if (str_replace("hello","gif",$myvar) == true) 
{ 
    $myvar = str_replace("hello","gif",$myvar); 
} 
+0

您可能只需使用'strpos()!== false'来检查,然后使用'str_replace()'。请参阅'strpos()'使用手册:http://php.net/manual/en/function.strpos.php – Rasclatt

+1

你的代码没有意义; 'str_replace()'不返回布尔值。 – SLaks

+1

根据to [docs](http://php.net/manual/en/function.str-replace.php),'str_replace'返回_该函数返回一个字符串或一个替换值的数组。_所以,它永远不会评估为“假”。 –

回答

3

简单的解决方案是:

// if you have `hello` in a string - replace it 
if (strpos($myvar, 'hello') !== false) { 
    $myvar = str_replace("hello","jpg",$myvar); 
} else { 
    // else replace `hi`, 
    // if there's no `hi` in a string - it doesn't matter 
    $myvar = str_replace("hi","gif",$myvar); 
} 
+0

好主意,但意识到我的字符串将永远不会有嗨,只有你好。 +1虽然。 – irishwill200

2
$myvar = (strpos($myvar, 'hello') !== false) ? str_replace('hello', 'jpg', $myvar) : str_replace('hi', 'gif', $myvar); 

OR

if (strpos($myvar, 'hello') !== false) 
{ 
    $myvar = str_replace('hello', 'jpg', $myvar); 
} 
elseif (strpos($myvar, 'hi') !== false) 
{ 
    $myvar = str_replace('hi', 'gif', $myvar); 
} 
+0

好主意,但意识到我的字符串将永远不会嗨,但只有你好。我更新了我的问题。甚至没有注意到错字! +1虽然。 – irishwill200

0

或者只是使用数组:

$myvar = str_replace(array('hello', 'hi'), array('jpg', 'gif'), $myvar);