When someone writes:
"Near Tokyo"
I would like to check first if the $search contains "near" and if it does then take the "Tokyo" into a variable $location.
I tried this:
if(strpos($search, 'near') == true){
$search = explode("near ", $location);
echo $location;
exit();
}
did not work, it does not execute the if statement
You have multiple bugs here:
strpos may return 0, which signifies a match but will not compare equal to true
strpos is case-sensitive, which would make your example not work (look into stripos instead)
explode is also case-sensitive
It would probably be easiest to use a regex for this:
$input = "Near Tokyo";
if (preg_match('/near\s+(\w+)/i', $input, $matches)) {
echo "Near: ".$matches[1]."\n";
}
else {
echo "No match.\n";
}
See it in action.
This particular regex will only match the next word after "near", but this can be modified to suit your requirements.
returntype of strpos is int, not bool
http://php.net/manual/en/function.strpos.php
so use (according to manual pages) this:
if(strpos($search, 'near') !== false)
change it to:
if(strpos($search, 'near') !== false){
$search = explode("near ", $location);
echo $location;
exit();
}
just take a look at the documentation where this behaviour is explained:
It is easy to mistake the return values for "character found at
position 0" and "character not found". Here's how to detect the
difference:
<?php
$pos = strrpos($mystring, "b");
if ($pos === false) { // note: three equal signs
// not found...
}
?>
Yes, strpos, cumbersome boolean result handling. You probably should or should want to use stristr instead, which is also case-insensitive:
if (stristr($search, "Near")) {
And since you are extracting text anyway, why not use a regex? (People are using the awful explode workaround way too often.)
if (preg_match("'Near (\S+)'i", $search, $match)) {
echo $match[1];
}
use this to get a result:
if(strpos($search, 'near') !== false){
$location = explode("near ", $search);
print_r($location);
exit();
}
$search = "Near Tokyo";
if(strpos($search, 'Near') === 0){
$location = explode("Near ", $search);
echo $location[1];
exit();
}
<?php
$search = "Near Tokoyo";
if(preg_match("/near ([a-z]+)/i", $search, $match))
{
$location = $match[1];
echo $location;
}
?>
EDIT:
Fixed some bugs in your code.
if(stripos($search, 'near') !== false){
$location = explode("near ", $search);
echo $location[0];
exit();
}
Related
I am trying to write a script with PHP where it'll open up a text file ./urls.txt and check each domain for a specific word. I am really new to PHP.
Example:
Look for the word "Hello" in the following domains.
List:
Domain1.LTD
Domain2.LTD
Domain3.LTD
and just simply print out domain name + valid/invalid.
<?PHP
$link = "http://yahoo.com"; //not sure how to loop to read each line from a file.
$linkcontents = file_get_contents($link);
$needle = "Hello";
if (strpos($linkcontents, $needle) == false) {
echo "Valid";
} else {
echo "Invalid";
}
?>
$arrayOfLinks = array(
"http://example.com/file.txt",
"https://www.example-site-2.com/files/file.txt"
);
$needle = "Hello";
foreach($arrayOfLinks as $link){ // loop through the array
$linkcontents = file_get_contents($link);
if (stripos($linkcontents , $needle) !== false) { // stripos is case-insensitive search
// the needle exists in $linkcontents
// !== false instead of != false since stripos can return 0 meaning the needle is the first word of the contents
echo "Valid";
} else {
// the word does not exist in the given text
echo "Invalid";
}
}
First of all use CURL in favor of file_get_contents() because of security.
This would be a correct strpos example:
//your previous code
if (strpos($linkcontents, $needle) !== false) { // see the !==
echo "Valid"; //Needle found
} else {
echo "Invalid"; //Needle not found
}
For more complex crawling you could use some regexp instead of strpos.
When i search for "bank", it should display Bank-List1, Bank-List2 from the following list.
Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.
Is there is any php function to display?
I got the output for exact match. But no result for this type of search.
Please help me to find the solution.
you can use stristr
stristr — Case-insensitive strstr()
<?php // Example from PHP.net
$string = 'Hello World!';
if(stristr($string, 'earth') === FALSE) {
echo '"earth" not found in string';
}
// outputs: "earth" not found in string
?>
So for your situation, if your list was in an array named $values
you could do
foreach($values as $value)
{
if(stristr($value, 'bank') !== FALSE)
{
echo $value."<br>";
}
}
You can do it using stristr. This function returns all of haystack starting from and including the first occurrence of needle to the end. Returns the matched sub-string. If needle is not found, returns FALSE.
Here is the complete code:
<?php
$str="Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1";
$findme="bank";
$tokens= explode(",", $str);
for($i=0;$i<count($tokens);$i++)
{
$trimmed =trim($tokens[$i]);
$pos = stristr($trimmed, $findme);
if ($pos === false) {}
else
{
echo $trimmed.",";
}
}
?>
DEMO
This solution is only valid for this pattern of text is like: word1, word2, word3
<?php
$text = 'Railway-List, Bank-List1, Bank-List2, Education, Ecommerce, Articles, Railway-List1.';
function search_in_text($word, $text){
$parts = explode(", ", $text);
$result = array();
$word = strtolower($word);
foreach($parts as $v){
if(strpos(strtolower($v), $word) !== false){
$result[] = $v;
}
}
if(!empty($result)){
return implode(", ", $result);
}else{
return "not found";
}
}
echo search_in_text("bank", $text);
echo search_in_text("none", $text);
?>
output:
Bank-List1, Bank-List2
not found
This question already has answers here:
Using an array as needles in strpos
(16 answers)
Closed 9 years ago.
Im running strpos on a <a> tag to see if it contains either one of two urls.
At the moment im using this bellow - how would i set it to check if - tumblr.com OR google.com were present ?
function find_excluded_url ($url) {
$find = "tumblr.com"; // OR GOOGLE.COM ....
$pos = strpos($url, $find);
if ($pos === false) {
return false;
} else {
return true;
}
}
// SET URL
$url = "<a href='http://tumblr.com/my_post' rel='nofollow'>This site</a>";
// CALL FUNC
$run_url = find_excluded_url($url);
if ($run_url == true) {
echo "URL - " . $url . "<br>";
}
You can't use two needles in strpos. But what you can do, is use it twice, with an or:
function find_excluded_url ($url) {
return (strpos($url, "tumblr.com")!==false) || (strpos($url, "google.com")!==false);
}
For more complicated searches, you might want to look into Regular Expressions. This would work:
$subject = 'blablabgoogle
balblabtumblrasd
blaasdgoogleadsad';
$pattern = '#(?:google\.com|tumblr\.com)#i';
$result = preg_match($pattern, $subject, $subpattern, PREG_OFFSET_CAPTURE);
if($result) echo 'Position: ' . $subpattern[0][1];
The performance of this (if performance is an issue for you) depends on how many search queries you have and how big your haystack is. Regular expressions come with a relatively big overhead, however, they only have to run over the text once. If you use strpos twice, this gets expensive with long strings. If performance is really an issue, you could also write your own strpos that goes character per character. I doubt, however, that this is necessary.
function find_excluded_url ($url, $searchURL) {
$pos = strpos($url, $searchURL);
if ($pos === false) {
return false;
} else {
return true;
}
}
// SET URL
$url = "<a href='http://tumblr.com/my_post' rel='nofollow'>This site</a>";
// CALL FUNC
$run_url = find_excluded_url($url, 'google.com');
if ($run_url == true)
echo "URL - " . $url . "<br>";
$run_url = find_excluded_url($url, 'tumblr.com');
if ($run_url == true)
echo "URL - " . $url . "<br>";
I am trying to search through a URL for a matching string, but the below code snippet doesn't seem to work.
<?php
$url = "http://www.drudgereport.com";
$search = "a";
$file = file($url);
if (in_array($search,$file)) {
echo "Success!";
} else {
echo "Can't find word.";
}
?>
If you are just searching for an occurrence of a string on the page, you can use
$str = file_get_contents($url);
if (strpos($str, $search) !== false) {
echo 'Success!';
} else {
echo 'Fail';
}
in_array() checks if an array member is equal to your needle.
It is improbable many websites will have a line which is equal to a only.
Also, is allow_url_fopen enabled?
That code will only find a line that has the exact $search string (likely including whitespace). If you're parsing HTML, check PHP's DOMDocument classes. Or, you can use a regex to pull what you need.
As #alex says, check is allow_url_fopen is enabled.
Also you can use strpos to search the string:
<?php
$url = "http://www.drudgereport.com";
$search = "a";
$file_content = file_get_contents($url);
if (strpos($file_content, $search) !== false) {
echo "Success!";
} else {
echo "Can't find word.";
}
?>
$bodytext = "we should see this text <more> but not this at all <html>";
if(stristr($bodytext, "<more>") == TRUE)
{
$find = "<more>";
$pos = stripos($bodytext, $find);
$bodytext = substr($bodytext, 0, $pos);
}
echo "$bodytext";
If the $bodytext contains other html code, this also causes the above code to return true :
<more
more>
How do I adjust my code so only (and exactly) :
<more>
returns true?
Simple/naiive:
$bodytext = preg_replace('/(.*?)<more>.*/', $1, $bodytext);
stristr returns all of the string from the match to the end of the string. If a match is not found, it returns false.
You therefore need to do this:
if(stristr($bodytext, "<more>") !== false) {
// match found
}
stripos is more suited to your needs:
$pos = stripos($bodytext, "<more>");
if($pos !== false) {
// match found
}
Alternative: See Marc B's answer, which does everything you appear to be trying to achieve in a single statement.
You could also use the explode function and output the first element of the array
$bodytext = "we should see this text <more> but not this at all <html>";
if(stristr($bodytext, "<more>") == TRUE)
{
$split = explode('<more>', $bodytext);
echo $split[0];
}