If I look out for war that would also be found if I check Award:
$title = "Music award";
if (strpos($title, 'war') !== false) {
echo "found";
}
If I look for war I don't want to find award
Use regex matching
$title = "Music award";
if (preg_match('/\bwar\b/', $title) !== false) {
echo "found";
}
<?php
$string = "We are the music makers and we are the dreamers of dreams.";
$words = str_word_count($string, 1);
var_dump(in_array('music', $words));
var_dump(in_array('dream', $words));
Output:
bool(true)
bool(false)
Related
Lets say I have an array of bad words:
$badwords = array("one", "two", "three");
And random string:
$string = "some variable text";
How to create this cycle:
if (one or more items from the $badwords array is found in $string)
echo "sorry bad word found";
else
echo "string contains no bad words";
Example:
if $string = "one fine day" or "one fine day two of us did something", user should see sorry bad word found message.
If $string = "fine day", user should see string contains no bad words message.
As I know, you can't preg_match from array. Any advices?
How about this:
$badWords = array('one', 'two', 'three');
$stringToCheck = 'some stringy thing';
// $stringToCheck = 'one stringy thing';
$noBadWordsFound = true;
foreach ($badWords as $badWord) {
if (preg_match("/\b$badWord\b/", $stringToCheck)) {
$noBadWordsFound = false;
break;
}
}
if ($noBadWordsFound) { ... } else { ... }
Why do you want to use preg_match() here?
What about this:
foreach($badwords as $badword)
{
if (strpos($string, $badword) !== false)
echo "sorry bad word found";
else
echo "string contains no bad words";
}
If you need preg_match() for some reasons, you can generate regex pattern dynamically. Something like this:
$pattern = '/(' . implode('|', $badwords) . ')/'; // $pattern = /(one|two|three)/
$result = preg_match($pattern, $string);
HTH
If you want to check each word by exploding the string into words, you can use this:
$badwordsfound = count(array_filter(
explode(" ",$string),
function ($element) use ($badwords) {
if(in_array($element,$badwords))
return true;
}
})) > 0;
if($badwordsfound){
echo "Bad words found";
}else{
echo "String clean";
}
Now, something better came to my mind, how about replacing all the bad words from the array and check if the string stays the same?
$badwords_replace = array_fill(0,count($badwords),"");
$string_clean = str_replace($badwords,$badwords_replace,$string);
if($string_clean == $string) {
echo "no bad words found";
}else{
echo "bad words found";
}
Here is the bad word filter I use and it works great:
private static $bad_name = array("word1", "word2", "word3");
// This will check for exact words only. so "ass" will be found and flagged
// but not "classic"
$badFound = preg_match("/\b(" . implode(self::$bad_name,"|") . ")\b/i", $name_in);
Then I have another variable with select strings to match:
// This will match "ass" as well as "classic" and flag it
private static $forbidden_name = array("word1", "word2", "word3");
$forbiddenFound = preg_match("/(" . implode(self::$forbidden_name,"|") . ")/i", $name_in);
Then I run an if on it:
if ($badFound) {
return FALSE;
} elseif ($forbiddenFound) {
return FALSE;
} else {
return TRUE;
}
Hope this helps. Ask if you need me to clarify anything.
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
Lets say I have an array of bad words:
$badwords = array("one", "two", "three");
And random string:
$string = "some variable text";
How to create this cycle:
if (one or more items from the $badwords array is found in $string)
echo "sorry bad word found";
else
echo "string contains no bad words";
Example:
if $string = "one fine day" or "one fine day two of us did something", user should see sorry bad word found message.
If $string = "fine day", user should see string contains no bad words message.
As I know, you can't preg_match from array. Any advices?
How about this:
$badWords = array('one', 'two', 'three');
$stringToCheck = 'some stringy thing';
// $stringToCheck = 'one stringy thing';
$noBadWordsFound = true;
foreach ($badWords as $badWord) {
if (preg_match("/\b$badWord\b/", $stringToCheck)) {
$noBadWordsFound = false;
break;
}
}
if ($noBadWordsFound) { ... } else { ... }
Why do you want to use preg_match() here?
What about this:
foreach($badwords as $badword)
{
if (strpos($string, $badword) !== false)
echo "sorry bad word found";
else
echo "string contains no bad words";
}
If you need preg_match() for some reasons, you can generate regex pattern dynamically. Something like this:
$pattern = '/(' . implode('|', $badwords) . ')/'; // $pattern = /(one|two|three)/
$result = preg_match($pattern, $string);
HTH
If you want to check each word by exploding the string into words, you can use this:
$badwordsfound = count(array_filter(
explode(" ",$string),
function ($element) use ($badwords) {
if(in_array($element,$badwords))
return true;
}
})) > 0;
if($badwordsfound){
echo "Bad words found";
}else{
echo "String clean";
}
Now, something better came to my mind, how about replacing all the bad words from the array and check if the string stays the same?
$badwords_replace = array_fill(0,count($badwords),"");
$string_clean = str_replace($badwords,$badwords_replace,$string);
if($string_clean == $string) {
echo "no bad words found";
}else{
echo "bad words found";
}
Here is the bad word filter I use and it works great:
private static $bad_name = array("word1", "word2", "word3");
// This will check for exact words only. so "ass" will be found and flagged
// but not "classic"
$badFound = preg_match("/\b(" . implode(self::$bad_name,"|") . ")\b/i", $name_in);
Then I have another variable with select strings to match:
// This will match "ass" as well as "classic" and flag it
private static $forbidden_name = array("word1", "word2", "word3");
$forbiddenFound = preg_match("/(" . implode(self::$forbidden_name,"|") . ")/i", $name_in);
Then I run an if on it:
if ($badFound) {
return FALSE;
} elseif ($forbiddenFound) {
return FALSE;
} else {
return TRUE;
}
Hope this helps. Ask if you need me to clarify anything.
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();
}
Is there any way to tell if a preg_replace was successful or not?
I tried:
<?php
$stringz = "Dan likes to eat pears and his favorite color is green and green!";
$patterns = array("/pears/","/green/", "/red/");
if ($string = preg_replace($patterns, '<b>\\0</b>', $stringz, 1)) {
echo "<textarea rows='30' cols='100'>$string</textarea>";
}else{
echo "Nope. You didn't have all the required patterns in the array.";
}
?>
and yes, I looked at php docs for this one. Sorry about my stupid questions earlier.
You can use the last param of preg_replace: &$count, which will contain the number of replacements that were done:
$stringz = "Dan likes to eat pears and his favorite color is green and green!";
$patterns = array("/pears/","/green/","/green/");
$new_patterns = array();
foreach ($patterns as $p)
if (array_key_exists($p, $new_patterns))
$new_patterns[$p]++;
else
$new_patterns[$p] = 1;
$string = $stringz;
$success = TRUE;
foreach ($new_patterns as $p => $limit)
{
$string = preg_replace($p, '<b>\\0</b>', $string, $limit, $count);
if (!$count)
{
$success = FALSE;
break;
}
}
if ($success)
echo "<textarea rows='30' cols='100'>$string</textarea>";
else
echo "Nope. You didn't have all the required patterns in the array.";
edited to fix the issue when there are two of the same in $patterns
if (preg_replace($patterns, '<b>$0</b>', $stringz, 1) != $stringz)
echo 'preg_replace was successful'
From the documentation:
If matches are found, the new subject
will be returned, otherwise subject
will be returned unchanged or NULL if
an error occurred.
So:
$string = preg_replace($patterns, '<b>\\0</b>', $stringz, 1);
if($string != $stringz) {
// something was replaced
}