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 ...
}
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
}
I would like to find part of a string and if true I want to ouput the whole of the string that it finds.
Below is an example:
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
if(strstr($Find, $Towns)){
echo outputWholeString($Find, $Towns); // Result: Eccleston.
}
If anyone can shed some light on how to do this as well, and bare in mind that it will not be static values; the $Towns and $Find variables will be dynamically assigned on my live script.
Use explode() and strpos() as
$Towns = "Eccleston, Aberdeen, Glasgow";
$data=explode(",",$Towns);//
$Find = "Eccle";
foreach ($data as $town)
if (strpos($town, $Find) !== false) {
echo $town;
}
DEMO
You have to use strpos() to search for a string inside another one:
if( strpos($Towns, $Find) === false ) {
echo $Towns;
}
Note that you have to use "===" to know if strpos() returned false or 0.
The solution using preg_match function:
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
preg_match("/\b\w*?$Find\w*?\b/", $Towns, $match);
$result = (!empty($match))? $match[0] : "";
print_r($result); // "Eccleston"
Assuming that you will always have $Towns separated by ", " then you could do something like this
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
$TownsArray = explode(", ", $Towns);
foreach($TownsArray as $Town)
{
if(stristr($Find, $Town))
{
echo $Town; break;
}
}
The above code will output the Town once it finds the needle and exit the foreach loop. You could remove the "break;" to continue letting the script run to see if it finds more results.
Using preg_match(), it is possible to search for Eccle and return the Eccleston word.
I use the Pearl Compatible Regular Expression (PCRE) '#\w*' . $Find . '\w*#' in the code below and the demo code.
The # characters are PCRE delimiters. The pattern searched is inside these delimiters. Some people prefer / as delimiter.
The \w indicates word characters.
The * indicates 0 or more repetions of the previous character.
So, the #\w*Eccle\w*# PCRE searches for an string containing Eccle surrounded by one or more word characters (letters)
<?php
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
if (preg_match('#\w*' . $Find . '\w*#', $Towns, $matches)) {
print_r($matches[0]);
}
?>
Running code: http://sandbox.onlinephpfunctions.com/code/4e4026cbbd93deaf8fef0365a7bc6cf6eacc2014
Note: '#\w*' . $Find . '\w*#' is the same as "#\w*$Find\w*#" (note the surrounding single or double quotes). See this.
You were nearly there...
This is probably what you are looking for:
<?php
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
if(stripos($Towns, $Find)) {
echo $Towns;
}
The output is: Eccleston, Aberdeen, Glasgow which is what I would call "the whole string".
If however you only want to output that partly matched part of "the whole string", then take a look at that example:
<?php
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";
foreach (explode(',', $Towns) as $Town) {
if(stripos($Town, $Find)) {
echo trim($Town);
}
}
The output of that obviously is: Eccleston...
Two general remarks:
the strpos() / stripos() functions are better suited here, since they return only a position instead of the whole matched string which is enough for the given purpose.
the usage of stripos() instead of strpos() performs a case insensitive search, which probably makes sense for the task...
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.
I want to check the first word of some sentences. If the first word are For, And, Nor, But, Or, etc, I want to skip the sentence.
Here's the code :
<?php
$sentence = 'For me more';
$arr = explode(' ',trim($sentence));
if(stripos($arr[0],'for') or stripos($arr[0],'but') or stripos($arr[0],'it')){
//doing something
}
?>
Blank result, Whats wrong ? thank you :)
Here, stripos will return 0 if the word is found (found at position 0).
It returns false if the word is not found.
You should write :
if(stripos($arr[0],'for') !== false or stripos($arr[0],'but') !== false or stripos($arr[0],'it') !== false){
//skip
}
Stripos returns the position on the first occurrence of the needle in the haystack
The first occurrence is at position 0, which evaluates to false.
Try this as an alternative
$sentence = 'For me more';
// make all words lowercase
$arr = explode(' ', strtolower(trim($sentence)));
if(in_array($arr[0], array('for', 'but', 'it'))) {
//doing something
echo "found: $sentence";
} else {
echo 'failed';
}
Perhaps use preg_filter if you are going to know what the string to be evaluated is (i.e. you don't need to parse out sentences).
$filter_array = array(
'/^for\s/i',
'/^and\s/i',
'/^nor\s/i',
// etc.
}
$sentence = 'For me more';
$result = preg_filter(trim($sentence), '', $filter_array);
if ($result === null) {
// this sentence did not match the filters
}
This allows you to determine a set of filter regex patterns to see if you have a match. Note that in this case I just used '' as "replacement" value, as you don't really care about actually making a replacement, this function just gives you a nice way to pas in an array of regular expressions.
i am using preg_replace for highlighting words in search results. search result sometimes also contains URL, not just text. and some URLs contain key words. then URLs get messed up as preg_replace also changes the URL.
is there any way to ignore URLs in preg_replace?
this is what i use:
$result = preg_replace('!('.$keyword.')!i', '<span style="background: #f00;">$1</span>', $result);
thank you!
Edited..
okay, than is this helpful?
Make your result as array and then check if it contains url?
<?php
$result = "This is Stpartāāa http://google.lv ";
$arr = explode(" ", $result);
foreach($arr as $key => $value) {
if ((strpos($value,'http://') !== false) AND (strpos($value,'www.') !== false)) {
// do nothing
} else {
// do somthing
}
}
?>