Php how to do if str_replace?

$str - some value in foreach.

 $str = str_replace('_name_','_title_',$str); 

how to do if str_replace ?

I want to do the thing if have a str_replace , then echo $str , otherwise not, move the current foreach, and then to the next. Thanks.

+6
source share
3 answers

There is a fourth parameter str_replace() , which is set to the number of replacements made. If nothing has been replaced, it is set to 0. Drop the reference variable here, and then check it in the if statement:

 foreach ($str_array as $str) { $str = str_replace('_name_', '_title_', $str, $count); if ($count > 0) { echo $str; } } 
+18
source

If you need to check if a string is found in another string, you might like this.

 <?php if(strpos('_name_', $str) === false) { //String '_name_' is not found //Do nothing, or you could change this to do something } else { //String '_name_' found //Replacing it with string '_title_' $str = str_replace('_name_','_title_',$str); } ?> 

http://php.net/manual/en/function.strpos.php

However, for this example you do not need. If you run str_replace on a line that does not replace anything, it will not find anything to replace and will simply move without any replacements or changes.

Good luck.

+5
source

I know these are old questions, but this gives me guidance to solve my own verification problem, so my solution was:

 $contn = "<p>String</p><p></p>"; $contn = str_replace("<p></p>","",$contn,$value); if ($value==0) { $contn = nl2br($contn); } 

Great for me. Hope this is helpful to someone else.

0
source

Source: https://habr.com/ru/post/889828/


All Articles