I'm trying to find a string inside a variable. The problem is that it doesn't look for a unique string.
For example, a have a variable with the following values:
$mystring = "p,pp,m,g";
Here's the code that I'm using:
<?php
$find="pp";
if(strstr($mystring, $find)==true){
echo "found";
}
?>
The problem is: when I'm looking for pp, it also returns "p" as a result.
How can I avoid this kind of error?
I'm using it to check the sizes of a item on an ecommerce website and I'm struggling to get it right.
Any ideas?!
Use strpos. Make sure you use the !== operator.
echo strpos($mystring, $find) !== false ? 'found' : 'not found';
$mystring = "p,pp,m,g";
$str = explode(",",$mystring);
$find = "/^pp$/";
foreach($str as $val){
if(preg_match($find, $val)){
echo "found => ".$val;
}else{
echo "not found";
}
}
ref: http://php.net/manual/en/function.preg-match.php
You can use transformating to array and search as array's element:
$mystring = "p,pp,m,g";
$arr = explode(',',$mystring);
if (in_array('p',$arr,true)) {echo "found";}
Or (http://php.net/manual/en/function.strstr.php: "If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead") you can write
if (strpos($mystring,'pp')!==false) {echo 'found';} else {echo 'not found';}
Just changed the values and used the same strstr function to avoid similar letters problem.
Related
I am a new person in the PHP. I have one String.I use this to find a word for strpos function
for example..
$a= "google" ;
$b= "google is best one" ;
if(strpos($b, $a) !== false) {
echo "true, " ; // Working Fine...
}
so i want to in this case check My Example
$a= "google,yahoo,Bing" ;
$b= "Bing is Good " ;
if(strpos($b, $a) !== false) {
echo "true, " ; // I Need True...
}
This is how you do PHP
Split the string on the comma using explode() and then check each of the parts individually:
$a= "google,yahoo,Bing" ;
$b= "Bing is Good " ;
$parts = explode(',', $a);
foreach ($parts as $part) {
if(strpos($b, $part) !== false) {
echo "true, " ; // I Need True...
}
}
To clarify, it looks like you're trying to perform a match such that any value in a list of values from $a is present in $b. This is not possible with a simple strpos() call because strpos() looks for the exact occurrence of the string you're passing in.
What you're attempting to do is a pattern-based search. To make this work, please look into using a regular expression with preg_match(). Such an example could look like this:
$pattern = '/google|yahoo|Bing/';
$target_string = 'Bing is good';
if(preg_match($pattern, $target_string)) {
echo "true, ";
}
For more information, look into regular expression syntax and play around with it until you're familiar with how they work.
Like Patrick Q said put names in an array example is here
becuase you are searching all three words "google,yahoo,Bing" which can not be true.
but for beginner to understand other way.
$a[0]= "google";
$a[1]= "yahoo";
$a[2]= "Bing";
$b= "Bing is Good";
strpos($b, $a[0]); // false
strpos($b, $a[1]); // false
strpos($b, $a[2]); // true as Bing found
also you can loop through to check
You can solve your issue with a regular expression:
if (preg_match('/string1|string2|string3/i', $str)){
//if one of them found
}else{
//all of them can not found
}
Ok, its easier to explain like this.
I have a variable:
$string
I also have have substring variables:
$sub1, $sub2, $sub3, $sub4
I need to echo $string if any of the substring variables are found. Including if multiple substring variables are found.
I am using this to find substrings:
if (strpos($filename, $clothes) > 0 {
echo $string
}
The thing thats confusing me mostly is returning $string if there are all OR just some of the substrings.
First, for sake of simplicity, consider those substring variables as an array.
Now, the code may look like this,
function doIt($string, $sub_strings){
foreach($sub_strings as $substr){
if(strpos($string, $substr) !== FALSE)
{
return $string; // at least one of the needle strings are substring of heystack, $string
}
}
return ""; // no sub_strings is substring of $string.
}
and to use this function,
echo doIt($string,array($str1,$str2,$str3,$str4));
Thanks to Orangepill!
Just create a function that tests each value in an array against the string and return true if any are found.
function findOneOf(array $terms, $string){
foreach ($terms as $term){
if (strpos($string, $term) !== FALSE){
return true;
}
}
return false;
}
Then you can do your test like
if (findOneOf(array($sub1, $sub2, $sub3,$sub4), $string)){
echo $string;
}
I currently have a problem. I have a code that looks like the one below and I want an operator that checks if a part of a query is present in an array. This is the code that I have:
<?php
$search = 'party hat';
$query = ucwords($search);
$string = file_get_contents('http://clubpenguincheatsnow.com/tools/newitemdatabase/items.php');
$string = explode('<br>',$string);
foreach($string as $row)
{
preg_match('/^(\D+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/', trim($row), $matches);
if($matches[1] == "$query")
{
echo "<a href='http://clubpenguincheatsnow.com/tools/newitemdatabase/info.php?id=$matches[2]'>";
echo $matches[1];
echo "</a><br>";
}
}
?>
What I want to do is instead of if($matches[1] == "$query") to check if both are identical, I want my code to see if a PART of $query exists in $matches[1]. How do I do this though? Please help me!
You can use strpos to test if a string is contained in another string:
if(strpos($matches[1], $query) !== false)
If you prefer it to be case insensitive, use stripos instead.
If you want to check if $query is a substring of $matches[1], you can use
strpos($matches[1], $query) !== false
(see documentation for why you must use !==).
You can use strstr to test if a string contains another string:
if(strstr($matches[1], $query)) {
// do something ...
}
How do I find exact 2, in a string using strpos? Is it possible using strpos? The example below returns "Found" even though the match is NOT exact to what I need. I understand 2, is matching with 22,. It should return "Not Found". I am matching ID's in this example.
$string = "21,22,23,26,";
$find = "2,";
$pos = strpos($string, $find);
if ($pos !== false) {
echo "Found";
} else {
echo "Not Found";
}
Unless the string is enormous, make an array and search it:
$string = "21,22,23,26,";
$arr = explode(",", $string);
// array_search() returns its position in the array
echo array_search("2", $arr);
// null output, 2 wasn't found
Actually, in_array() is probably faster:
// in_array() returns a boolean indicating whether it is found or not
var_dump(in_array("2", $arr));
// bool(false), 2 wasn't found
var_dump(in_array("22", $arr));
// bool(true), 22 was found
This will work as long as your string is a comma-delimited list of values. If the string is really long, making an array may be wasteful of memory. Use a string manipulation solution instead.
Addendum
You didn't specify, but if by some chance these strings came from a database table, I would just add that the appropriate course of action would be to properly normalize it into another table with one row per id rather than store them as a delimited string.
Try with explode and in_array
Example:
$string = "21,22,23,26,";
$string_numbers = explode(",", $string);
$find = 2;
if (in_array($find, $string_numbers)) {
echo "Found";
} else {
echo "Not Found";
}
You can use preg_match if you want to avoid arrays.
$string = "21,22,23,26,";
$find = '2';
$pattern = "/(^$find,|,$find,|,$find$)/";
if (0 === preg_match($pattern, $string)) {
echo "Not Found";
} else {
echo "Found";
}
This will find your id at beginning, middle or at the end of the string. Of course, I am assuming $string does not contain characters other than numbers and commas (like spaces).
$str is some value in a foreach.
$str = str_replace('_name_','_title_',$str);
how to make a if str_replace?
I want do the thing if have a str_replace then echo $str, else not, jump the current foreach then to the next. Thanks.
There is a fourth parameter to str_replace() that is set to the number of replacements performed. If nothing was replaced, it's set to 0. Drop a reference variable there, and then check it in your if statement:
foreach ($str_array as $str) {
$str = str_replace('_name_', '_title_', $str, $count);
if ($count > 0) {
echo $str;
}
}
If you need to test whether a string is found within another string, you can 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 you shouldn't need to, for this example. If you run str_replace on a string that has nothing to replace, it won't find anything to replace, and will just move on without making any replacements or changes.
Good luck.
I know this is an old question, but it gives me a guideline to solve my own checking problem, so my solution was:
$contn = "<p>String</p><p></p>";
$contn = str_replace("<p></p>","",$contn,$value);
if ($value==0) {
$contn = nl2br($contn);
}
Works perfectly for me.
Hope this is useful to someone else.