I want to match only the first letter of the string i.e 'bot'.
For ex:
It should run a function if user types "bot hi" and should not work if they type "hi bot there"
if(preg_match('[bot ]', strtolower($message))) {
$msg = str_replace('bot ', '', $message);
//Some message response
}
the above code works even if I type "hi bot there"
You should use the ^ for tell at begin of the string
if ( preg_match("/^bot (.*)/i", $message) ) {
$msg = str_replace('bot ', '', $message);
//Some message response
}
You can check this with strpos() :
$str = "bot hi";
if (0 === strpos($str, 'bot')) {
echo("str starts with bot");
else{
echo("str does not starts with bot");
}
}
Related
I've a log file that reads as
text message sent to client 1234 and mobileNo: 987654
Message: This is working
Confirmation No: ab123
text message sent to client 4321 and mobileNo: 456789
Message: This is not working
Confirmation No:
I have to get an alert if there is no confirmation number (i.e. Confirmation No: )
I've written the following code:
preg_match('/Confirmation No:\s*$/', $logLine, $match);
$matchLine = implode(" ",$match);
if ($matchLine == NULL) {
echo "There is an empty Confirmation No";
} else {
echo "Confirmation No: " . $matchLine;
}
This works fine and prints "There is an empty Confirmation No", if there is no confirmation.
But I would like to add clientID and MobileNo in the output too, i.e. There is an empty confirmation for client 4321 on MobileNo: 456789.
Can someone please advise, how can I do that?
Thanks in advance
preg_match("/Confirmation\sNo:\s(.*)..*client\s(\d+)\sand\smobileNo:\s(\d+)/ms", $string, $match);
if ($match[1] == "") {
echo "There is an empty Confirmation No for client " . $match[2] . " on MobileNo: " . $match[3];
} else {
echo "Confirmation No: " . $match[1];
}
https://regex101.com/r/qU7aP2/1
EDIT: I just noticed, maybe it's the other way around??
https://regex101.com/r/oY4hD9/1
$pattern = "/client\s(\d+)\sand\smobileNo:\s(\d+)..*Confirmation\sNo:\s(\w+)/ms";
I wasn't sure how the string was built.
Not that if this is the regex pattern you need then the code $match[x] needs to change places.
Here is how I'd do the job:
// within the loop on the log file
if (preg_match('/\b(client \d*) and \b(mobileNo: \d*)/', $logLine, $m)) {
$client = 'There is an empty confirmation for '.$m[1].' on '.$m[2];
}
if (preg_match('/Confirmation No: (\w*)$/', $logLine, $m) {
if (empty($m[1])) {
echo $client;
} else {
echo $logLine;
}
$client = '';
}
see this code below:
comes from: http://www.damnsemicolon.com/php/php-parse-email-body-email-piping
//get rid of any quoted text in the email body
$body_array = explode("\n",$body);
$message = "";
foreach($body_array as $key => $value){
//remove hotmail sig
if($value == "_________________________________________________________________"){
break;
//original message quote
} elseif(preg_match("/^-*(.*)Original Message(.*)-*/i",$value,$matches)){
break;
//check for date wrote string
} elseif(preg_match("/^On(.*)wrote:(.*)/i",$value,$matches)) {
break;
//check for From Name email section
} elseif(preg_match("/^On(.*)$fromName(.*)/i",$value,$matches)) {
break;
//check for To Name email section
} elseif(preg_match("/^On(.*)$toName(.*)/i",$value,$matches)) {
break;
//check for To Email email section
} elseif(preg_match("/^(.*)$toEmail(.*)wrote:(.*)/i",$value,$matches)) {
break;
//check for From Email email section
} elseif(preg_match("/^(.*)$fromEmail(.*)wrote:(.*)/i",$value,$matches)) {
break;
//check for quoted ">" section
} elseif(preg_match("/^>(.*)/i",$value,$matches)){
break;
//check for date wrote string with dashes
} elseif(preg_match("/^---(.*)On(.*)wrote:(.*)/i",$value,$matches)){
break;
//add line to body
} else {
$message .= "$value\n";
}
}
//compare before and after
echo "$body<br><br><br>$message";
$body contains the complete email body including quoted area if this is a reply, this loop removes quoted area to get new reply as $message. But as suggested there, loop is slow and better to use preg_replace instead. so how can I do?
replace patterns with what? should I remove foreach loop too? I created below without foreach loop but seems wrong? please advice.
$patterns = array(
"_________________________________________________________________",
"/^-*(.*)Original Message(.*)-*/i",
"/^On(.*)wrote:(.*)/i",
"/^On(.*)$fromName(.*)/i",
"/^On(.*)$toName(.*)/i",
"/^(.*)$toEmail(.*)wrote:(.*)/i",
"/^(.*)$fromEmail(.*)wrote:(.*)/i",
"/^>(.*)/i",
"/^---(.*)On(.*)wrote:(.*)/i");
$message = preg_replace($patterns, '', $body);
You already narrowed it down to a workable solution. Only a few things to fix:
As #mario commented, you need to set the /m modifier for ^s to match at the beggining of each line.
Your first pattern needs to be enclosed with delimiters, and anchored to ^ and to the end of line to mantain the same meaning as in the original code.
Include the newline chars in order to remove the whole line.
Make sure the variables $fromName, $fromEmail, etc. are set.
Once you get a match, match everything from there to the end of the body with (?s:.*).
Code:
$patterns = array(
"/^_{30,}$(?s:.*)/m",
"/^.*Original Message(?s:.*)/im",
"/^(?:---.*)?On .* wrote:(?s:.*)/im",
"/^On .* $fromName(?s:.*)/im",
"/^On .* $toName(?s:.*)/im",
"/^.*$toEmail(.*)wrote:(?s:.*)/im",
"/^.*$fromEmail.* wrote:(?s:.*)/im",
"/^>.*/ims",
);
$message = preg_replace($patterns, '', $body);
echo "$body<br><br><br>$message";
Run this code here
A word of advice:
Take into account that it will also strip lines like:
only thing I wrote: ...
We are trying to display whether a file contains a specific string or not:
Here we read the file:
$myFile = "filename.txt";
$fh = fopen($myFile,'r');
$theData = fread($fh, filesize("filename.txt"));
fclose($fh);
filename.txt contains "Offline"
Here we are trying to compare the strings:
if(strcmp($theData,"Online")==0){
echo "Online"; }
elseif(strcmp($theData,"Offline")==0) {
echo "Offline"; }
else {
echo "This IF is not working." }
We have tried using regular if without the strcomp, but it did not work either. I'm thinking that an IF cannot compare the results from the fread to a regular string. Perhaps we will need to try another method.
Any Ideas?
Use preg_match()
$string = "your-string";
$pattern = "/\boffline\b/i";
// The \b in the pattern indicates a word boundary, so only the distinct
// word "offline" is matched; if you want to match even partial word "offline"
// within some word, change the pattern to this /offline/i
if(preg_match($pattern, $string)) {
echo "A match was found.";
}
You can use strpos() as well (it is faster in this case)
$string = 'your-stringoffline';
$find = 'offline';
$pos = strpos($string, $find);
if($pos !== false){
echo "The string '$find' was found in the string '$string' at position $pos";
}else{
echo "The string '$find' was not found in the string '$string'";
}
regex is very slow when used to search in long strings. use strpos
$strFile = file_get_contents("filename.txt"); // load file
if(strpos($strFile, 'Online')!==false){ // check if "Online" exists
echo "We are Online";
}
elseif(strpos($strFile, 'Offline')!==false){ // check if "Offline" exists
echo "We are Offline";
}
else{ // other cases
echo "Status is unknown";
}
I put another way to do that (depending what it is inside the file), although it is not the best it may be useful in some circumstances
if (exec("grep Offline filename.txt") === 'Offline')
echo 'Offline';
else
echo 'Online';
Byee
Are you checked the value contains in $theData ?
Try something like this:
if(strcmp($theData,"Online") === 0)
echo $theData." is equal to string Online using case sensisive";
else if(strcmp($theData,"Offline") === 0)
echo $theData." is equal to string Offline using case sensisive";
else
echo $theData." This IF is not working.";
Here the doc for more infos: http://php.net//manual/en/function.strcmp.php
Or using the hex494D49's method: (Not tested)
function isStringAreTheSame($initialString, $stringToCompare) {
$pattern = "/\b".$initialString."\b/";
return preg_match($pattern, $stringToCompare);
}
Is it possible to shorten this code using preg_replace instead of preg_match?
I am using it to remove quoted text from an email body.
Quoted text being when you quote somebody when you reply to an email.
# Get rid of any quoted text in the email body
# stripSignature removes signatures from the email
# $body is the body of an email (All headers removed)
$body_array = explode("\n", $this->stripSignature($body));
$new_body = "";
foreach($body_array as $key => $value)
{
# Remove hotmail sig
if($value == "_________________________________________________________________")
{
break;
# Original message quote
}
elseif(preg_match("/^-*(.*)Original Message(.*)-*/i",$value,$matches))
{
break;
# Check for date wrote string
}
elseif(preg_match("/^On(.*)wrote:(.*)/i",$value,$matches))
{
break;
# Check for From Name email section
}
elseif(preg_match("/^On(.*)$fromName(.*)/i",$value,$matches))
{
break;
# Check for To Name email section
}
elseif(preg_match("/^On(.*)$toName(.*)/i",$value,$matches))
{
break;
# Check for To Email email section
}
elseif(preg_match("/^(.*)$toEmail(.*)wrote:(.*)/i",$value,$matches))
{
break;
# Check for From Email email section
}
elseif(preg_match("/^(.*)$fromEmail(.*)wrote:(.*)/i",$value,$matches))
{
break;
# Check for quoted ">" section
}
elseif(preg_match("/^>(.*)/i",$value,$matches))
{
break;
# Check for date wrote string with dashes
}
elseif(preg_match("/^---(.*)On(.*)wrote:(.*)/i",$value,$matches))
{
break;
# Add line to body
}
else {
$new_body .= "$value\n";
}
}
This almost works, but it keeps the first line "On Mon, Jul 30, 2012 at 10:54 PM, Persons Name wrote:"
$body = preg_replace('/(^\w.+:\n)?(^>.*(\n|$))+/mi', "", $body);
There's probably a more elegant way of doing this, but this should work (assuming the regexps are correct):
$search = array(
"/^-*.*Original Message.*-*/i",
"/^On.*wrote:.*/i",
"/^On.*$fromName.*/i",
"/^On.*$toName.*/i",
"/^.*$toEmail.*wrote:.*/i",
"/^.*$fromEmail.*wrote:.*/i",
"/^>.*/i",
"/^---.*On.*wrote:.*/i"
);
$body_array = explode("\n", $this->stripSignature($body));
$body = implode("\n", array_filter(preg_replace($search, '', $body_array)));
// or just
$body = str_replace(
array("\0\n", "\n\0"), '', preg_replace($search, "\0", $body)
);
Edit: As inhan pointed out, the dots in the email addresses (and potentially other special characters) need to be escaped using preg_quote() prior to being inserted into the patterns.
I having a issue filtering bad words inside a contact form message.
It strips all the message except the first letter of the word.
Any help?
below is just getting the info
<?php
$error = '';
if(!empty($_POST['username'])) $username = $_POST['username'];
if(!empty($_POST['email'])) $email = $_POST['email'];
if(!empty($_POST['subject'])) $subject = check($_POST['subject']);
if(!empty($_POST['message'])) $msg = filter($_POST['message']);
this is the function I am trying to use to strip the bad words and replace them
$bad_words = array(
'word1' => 'gosh',
'word2' => 'darn',);
function filter($matches) {
global $bad_words;
$replace = $bad_words[$matches[0]];
return !empty($replace) ? $replace : $matches[0];
}
checks the drop down options and doesn't allow certain subjects to be emailed.
function check($str){
global $error;
if ($str == 'Mean Spirited Comment'){
$error = 'You sent a Mean-Spirited Comment';
} else if ($str =='Political Comment'){
$error = 'You sent a Political Comment';
}
return $str;
}
places the info and sends
$to = 'email#email.com';
if (!empty($subject) && !empty($msg) && !empty($email) && !empty($username)){
if ($error == ''){
mail($to, $subject, $msg, 'From:' . $email);
} else {
print $error;
}
}
?>
You could use str_replace since it can take array.
For instance:
$message = "Hello there my good friends! I am very happy to see you all today even though I feel like crap.";
$badWords = array("Crap", "Damnit", "Frack");
echo str_replace($badWords, "*", $message);
Results would be: Hello there my good friends! I am very happy to see you all today even though I feel like *.
Why re-invent new methods when PHP already offers plenty of useful ones? This should be enough to remove "bad words" from messages being sent.