preg_replace successful or not - php

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
}

Related

How can I hide a string if it doesn't contain one of multiple words?

I already have a code:
<?
$eventname = $event->title;
$bad_words = array('Example1','Example2','Example3','Example4','Example5','Example6');
foreach($bad_words as $bad_word){
if(strpos($eventname, $bad_word) !== false) {
echo '';
break;
}
else {
echo '<div class="uk-text-contrast">'.translate('HIDDEN_INFO_DATE').'</div>';
break;
}
}
?>
this works, but only if the $eventname contains example1. But I want to hide echo '<div class="uk-text-contrast">'.translate('HIDDEN_INFO_DATE').'</div>'; from all of the defined words in the $bad_words.
How can I hide the echo if there is one of the $bad_words?
Why don't you use the in_array function? It's even shorter in that way.
if (in_array($eventname, $bad_words)) {
echo '';
} else {
echo '<div>';
}
remobe 'break' from code
foreach($bad_words as $bad_word){
if(strpos($eventname, $bad_word) !== false) {
echo '';
}
else {
echo '<div class="uk-text-contrast">'.translate('HIDDEN_INFO_DATE').'</div>';
}
}
I would convert the string $eventname to an array and then use the array Intersect function
$eventname = "sgswfdg Example1 sdfh dh dfa hadhadh";
$title_to_array=explode(" ", $eventname);
$bad_words = array('Example1','Example2','Example3','Example4','Example5','Example6');
$result = !empty(array_intersect($bad_words , $title_to_array ));
if ($result){
echo '';
} else {
echo $eventname;
}
Rather than using a loop, you could split the title into it's separate words and then check if there are any words in the $bad_words list using array_intersect()
// $eventname = $event->title;
$eventname = 'Some text';
$eventname = 'Some text Example1';
$bad_words = array('Example1','Example2','Example3','Example4','Example5','Example6');
$eventWords = explode(" ", $eventname);
if ( empty (array_intersect($eventWords, $bad_words))) {
// Event name is OK
echo $eventname;
}
This has some examples to show how it works.
Note that this code doesn't pick up things like Example1234 which strpos() would.
Update:
Just to make it more flexible, you can use regular expressions in case you have punctuation in the title...
$eventname = 'Some text';
$eventname = 'Some text,Example1';
$bad_words = array('Example1','Example2','Example3','Example4','Example5','Example6');
preg_match_all('/(\w+)/', $eventname, $eventWords);
if ( empty (array_intersect($eventWords[1], $bad_words))) {
echo '<div class="uk-text-contrast">'.translate('HIDDEN_INFO_DATE').'</div>';
}
( Note: Regular expressions aren't my subject so please let me know if this needs to be improved).

Check if multiple words exist in a sentence

I have the following :
Sentence :
"This is a red apple"
pattern to check :
red & apple.
Both sentence and pattern to check are user generated.
$sentence = "This is a red apple";
$words = array('red','apple');
$ch = implode("|",$words);
$pattern = '/[$ch]/';
if(preg_match($pattern, $sentence))
{
// Do something if the sentence contains red & apple
}
When i execute that code, i get nothing (nothing is displayed). When i do echo on $pattern it returns it as a whole string instead.
How can i fix this ? What am i missing ?
change $pattern = '/[$ch]/';
to
$pattern = '/('.$ch.')/'; or $pattern = '/['.$ch.']';
<?php
$sentence = "This is a red apple";
$words = array('apple','red');
$ch = implode("|",$words);
echo $pattern = '/('.$ch.')/';
if(preg_match($pattern, $sentence))
{
echo ' Do something if the sentence contains red & apple';
}else
{
echo 'nothing happpen';
}
?>
check if both word match
<?php
$sentence = "This is a red apple";
$words = array('red','apple');
$ch = implode("|",$words);
echo $pattern = '['.$ch.']';
if(preg_match_all($pattern, $sentence,$matches) == 2)
{
echo ' Do something if the sentence contains red & apple';
}else
{
echo 'nothing happpen';
}
?>
You also check how many word matched using
echo count($matches[0]);
$matches is array contain word are matched
You need to take care about quotes while using variables within quotes you need to update
$pattern = '/[$ch]/';
into
$pattern = "/($ch)/";
^^ ^^ ^^ ^^
You need to update your regex pattern also, so your code looks like as
$sentence = "This is a red apple";
$words = array('red','apple');
$ch = implode("|",$words);
$pattern = "/($ch)/";
if(preg_match_all($pattern, $sentence,$m))
{
echo "yes \n";
print_r($m);
}
Instead of regex I'll use array_intersect along with str_word_count like as
$sentence = "This is a red apple";
$words = array('red','apple','blue');
$var = count(array_intersect(str_word_count($sentence,1),$words));
if(count($words == $var)){
echo "Yes got it";
}
Demo
Demo2

Match one or more keywords defined in array [duplicate]

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.

Unable to make a 'related terms' code using strpos work in PHP

What I'm trying to do is get an input text from the user (for example lets say 'Java programmer') and trying to match this user input with a list of strings that I have stored in an array like 'Java programmer is a good boy', 'he plays ball at times', 'java and dogs hate each other', ' dogs are not java programmers'
I'm trying to do word matching so the program outputs a list of all strings in the array that match all words in user query (order isn't important)
So I want the output of the below code to be...
'Java programmer is a good boy'
'dogs are not java programmers'
Because these terms contain both 'java' and 'programmers' as per the query the user enters
Here's the code I wrote, it doesn't work. Any help will be much appreciated.
<?php
$relatedsearches = array();
$querytowords = array();
$string = "Java programmer"; //GET INPUT FROM USER
$querywords = (explode(' ', $string));
foreach($querywords as $z)
{
$querytowords[] = $z;
}
//ARRAY THAT STORES MASTER LIST OF QUERIES
$listofsearhches = array('Java programmer is a good boy', 'he plays ball at times', 'java and dogs hate each other', ' dogs are not java programmers');
foreach($listofsearhches as $c)
{
for ($i=0; $i<=(count($querytowords)-1); $i++)
{
if(strpos(strtolower($c), strtolower($querytowords[$i])) === true)
{
if($i=(count($querytowords)-1))
{
$relatedsearches[] = $c;
}
} else { break; }
}
}
echo '<br>';
if(empty($relatedsearches))
{
echo 'Sorry No Matches found';
}
else
{
foreach($relatedsearches as $lister)
{
echo $lister;
echo '<br>';
}
}
?>
I'd do something like this:-
$matches = array();
$string = 'java programmer';
$stringBits = explode(' ', $string);
$listOfSearches = array('Java programmer is a good boy', 'he plays ball at times', 'java and dogs hate each other', ' dogs are not java programmers');
foreach($listOfSearches as $l) {
$match = true;
foreach($stringBits as $b) {
if(!stristr($l, $b)) {
$match = false;
}
}
if($match) {
$matches[] = $l;
}
}
if(!empty($matches)) {
echo 'matches: ' . implode(', ', $matches);
} else {
echo 'no matches found';
}
So loop over the list of strings to search, set a flag ($match), then for every word in the $string check it exists somewhere in the current $listOfSearches string, if a word doesn't exist it will set the $match to false.
After checking for every word, if the $match is still true, add to the current string from $listOfSearches to the $matches array.
no need to explode the $string as you are looking for both the words java and programmer as a string 'Java programmer'. so your foreach need to look like this
foreach($listofsearhches as $c)
{
if(strpos(strtolower($c), strtolower($string)) === true)
{
$relatedsearches[] = $c;
} else { break; }
}
<?php
$string = "Java programmer"; //GET INPUT FROM USER
$querywords = (explode(' ', $string));
$relatedsearches = array();
$listofsearhches = array('Java programmer is a good boy', 'he plays ball at times', 'java and dogs hate each other', ' dogs are not java programmers');
foreach ($listofsearhches as $c) {
foreach($querywords as $word){
if(strpos(strtolower($c), strtolower($word)) !== false){
if(!in_array($c, $relatedsearches))
$relatedsearches[] = $c;
break;
}
}
}
echo '<br>';
if (count($relatedsearches) < 1) {
echo 'Sorry No Matches found';
}
else {
foreach ($relatedsearches as $lister) {
echo $lister;
echo '<br>';
}
}
?>
give it a go

preg_match array items in string?

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.

Categories