Good evening.
I'm making an IRC bot that responds when you mention him. What I want to know is how to make him reply when someone actually says his name. This is what I have so far ($match[3] is the message that someone said on a channel and yes, stripos is because I want it case-insensitive ):
if (stripos($match[3], "ircBot") !== false) {
$isMentioned = true;
}else { $isMentioned = false; }
while this does in fact detect if someone said his name, it only works if he's mentioned at the very beginning of the message so for example:
"ircBot is at the beginning of this sentance" would make $isMentioned true
"There's ircBot in between this sentance" would make $isMentioned false
"At the end of this sentance is ircBot" would make $isMentioned false
I want it to return true if "ircBot" is anywhere inside $match[3] and not just the beginning
You have to look for word boundaries to avoid someone called MircBot
// using in_array
$isMentioned = in_array('ircbot', preg_split('/\s+/', mb_strtolower($match[3])));
// using regex word boundaries
$isMentioned = preg_match('/\b(ircBot)\b/i', $match[3]);
http://3v4l.org/lh3JT
Use stristr instead
if (stristr($match[3], "ircBot") !== false) {
$isMentioned = true;
}else { $isMentioned = false; }
I think your error is somewhere else, e.g. the construction of $match[3]. This works fine:
$isMentioned = stripos('This is in the middle of ircBot the string','ircbot') !== false;
echo( $isMentioned ? 'Is Mentioned' : 'Sad ignored bot');
Related
I am building an automatic word moderation for the Discussion Forum that I am creating for a project. The automatic word moderation that I have right now works perfectly fine except if the input is not the exact same word as I put on the array. So say 'happy' is the word that I've put on the array, 'Happy' with the capital H will not be detected. Below is the code that I used.
if (isset($_POST['submit'])) {
$banned = array('shit','fuck','bastard','cunt', 'fuck you', 'piss');
$entry = $_POST['reply_content'];
mb_strtolower($banned);
foreach($banned as $word):
if (strpos($entry, $word) !== false){
echo 'Please use a more appropriate language.';
exit;
}
endforeach;
}
stripos() is what you need then, instead of strpos().
The i is for case insensitivity.
http://php.net/manual/en/function.stripos.php
There's always a way around the filter (H4PPY), but this will ignore caps and block the word anyway
if (isset($_POST['submit'])) {
$banned = array('shit','fuck','bastard','cunt', 'fuck you', 'piss');
$entry = strtolower(htmlentities(($_POST['reply_content'])));
mb_strtolower($banned);
foreach($banned as $word):
if($word == $entry) {
echo 'Please use a more appropriate language.';
exit;
}
endforeach;
}
I want to make sure the link is from the chosen social type.
help!!
$socialType = 'youtube';
$link = 'https://www.youtube.co.uk/watch?v=DBK-Cy9ge4M';
if (!preg_match("/^(http|https):\\/\\/[a-z0-9_]+$socialType*\\.[_a-z]{2,5}"."((:[0-9]{1,5})?\\/.*)?$/i",$link))
{
return Response::json('inValid');
}
{
return Response::json('Valid');
}
There will be two options as-
1. with preg_match -
$subject = "https://www.youtube.co.uk/watch?v=DBK-Cy9ge4M";
$pattern = '/^youtube/';
preg_match($pattern, substr($subject,7), $matches);
print_r($matches);
2. with strops as (Ruslan Osmanov)-
$socialType = 'youtube';
$link = 'https://www.youtube.co.uk/watch?v=DBK-Cy9ge4M';
if (strpos($link, $socialType) !== false) {
return Response::json('Valid');
}
You can simply check, if the link contains your substring using strpos:
$link = 'https://www.youtube.co.uk/watch?v=DBK-Cy9ge4M';
$type = 'youtube';
if (strpos($link, $type) !== false) {
// passed
}
Or use a simple regular expression, if you want stricter check:
$reg_type = preg_quote($type, '/');
if (preg_match("/^https?:\/\/(www\.)?$reg_type/", $link)) {
// passed
}
Note, you should escape values passed into the regular expression using preg_quote.
The pattern should be just enough. Don't overcomplicate. It's generally impossible to write a perfect regular expression. For example, it is very unlikely to find HTTP(S) protocol prefix + optional "www." + "youtube." in an URL not belonging to Youtube.
Also, I wouldn't expect to get the answer with a universal regular expression for all kinds of social networks. Each has its own pattern.
I already am using php's filter_var($email, FILTER_VALIDATE_EMAIL) to find out if the address is valid email.
I'm just gonna go ahead and block .ru email addresses. What regex and code should I use? Any other spammy tlds or addresses that you block would be appreciated as well.
I have tried this, but want to be sure I'm catching it correctly and catch other spammy emails.
function endsWith($haystack, $needle){
$length = strlen($needle);
return (substr($haystack, -$length) === $needle);
}
Thanks VG:
function russianEmail($email,$endings = array('\.ru')){
return (preg_match('/('.implode('|', $endings).')$/i', $email))?true:false;
}
You can match multiple domain zones (or just endings) with following code:
$endings = array('\.ru'); // you can add zones here
preg_match('/('.implode('|', $endings).')$/i', $email);
This regex is also case-insensitive.
This is what I use (not all my own work however):
Replace the link to russianbrides.com with whatever dark place you want to send the spammer.
function my_inArray($needle, $haystack) {
// this function allows wildcards in the array to be searched
foreach ($haystack as $value) {
if (true === fnmatch($value, $needle)) {
return true;
}
}
return false;
}
// Blocking Wildcard Emails.
$deny = array(
"*#hotmobilephoneoffers.com",
"*#*.ru",
"*#*.su",
);
if (my_inarray (strtolower($email_from), $deny)) {
header("location: http://www.russianbrides.com/");
exit();
}
The following code works with all YouTube domains except for youtu.be. An example would be: http://www.youtube.com/watch?v=ZedLgAF9aEg would turn into: ZedLgAF9aEg
My question is how would I be able to make it work with http://youtu.be/ZedLgAF9aEg.
I'm not so great with regex so your help is much appreciated. My code is:
$text = preg_replace("#[&\?].+$#", "", preg_replace("#http://(?:www\.)?youtu\.?be(?:\.com)?/(embed/|watch\?v=|\?v=|v/|e/|.+/|watch.*v=|)#i", "", $text)); }
$text = (htmlentities($text, ENT_QUOTES, 'UTF-8'));
Thanks again!
//$url = 'http://www.youtube.com/watch?v=ZedLgAF9aEg';
$url = 'http://youtu.be/ZedLgAF9aEg';
if (FALSE === strpos($url, 'youtu.be/')) {
parse_str(parse_url($url, PHP_URL_QUERY), $id);
$id = $id['v'];
} else {
$id = basename($url);
}
echo $id; // ZedLgAF9aEg
Will work for both versions of URLs. Do not use regex for this as PHP has built in functions for parsing URLs as I have demonstrated which are faster and more robust against breaking.
Your regex appears to solve the problem as it stands now? I didn't try it in php, but it appears to work fine in my editor.
The first part of the regex http://(?:www\.)?youtu\.?be(?:\.com)?/matches http://youtu.be/ and the second part (embed/|watch\?v=|\?v=|v/|e/|.+/|watch.*v=|) ends with |) which means it matches nothing (making it optional). In other words it would trim away http://youtu.be/ leaving only the id.
A more intuitive way of writing it would be to make the whole if grouping optional I suppose, but as far as I can tell your regex is already solving your problem:
#http://(?:www\.)?youtu\.?be(?:\.com)?/(embed/|watch\?v=|\?v=|v/|e/|.+/|watch.*v=)?#i
Note: Your regex would work with the www.youtu.be.com domain as well. It would be stripped away, but something to watch out for if you use this for validating input.
Update:
If you want to only match urls inside [youtube][/youtube] tags you could use look arounds.
Something along the lines of:
(?<=\[youtube\])(?:http://(?:www\.)?youtu\.?be(?:\.com)?/(?:embed/|watch\?v=|\?v=|v/|e/|[^\[]+/|watch.*v=)?)(?=.+\[/youtube\])
You could further refine it by making the .+ in the look ahead only match valid URL characters etc.
Try this, hope it'll help you
function YouTubeUrl($url)
{
if($url!='')
{
$newUrl='';
$videoLink1=$url;
$findKeyWord='youtu.be';
$toBeReplaced='www.youtube.com';
if(IsContain('watch?v=',$videoLink1))
{
$newUrl=tMakeUrl($videoLink1);
}
else if(IsContain($videoLink1, $findKeyWord))
{
$videoLinkArray=explode('/',$videoLink1);
$Protocol='';
if(IsContain('://',$videoLink1))
{
$protocolArray=explode('://',$videoLink1);
$Protocol=$protocolArray[0];
}
$file=$videoLinkArray[count($videoLinkArray)-1];
$newUrl='www.youtube.com/watch?v='.$file;
if($Protocol!='')
$newUrl.=$Protocol.$newUrl;
else
$newUrl=tMakeUrl($newUrl);
}
else
$newUrl=tMakeUrl($videoLink1);
return $newUrl;
}
return '';
}
function IsContain($string,$findKeyWord)
{
if(strpos($string,$findKeyWord)!==false)
return true;
else
return false;
}
function tMakeUrl($url)
{
$tSeven=substr($url,0,7);
$tEight=substr($url,0,8);
if($tSeven!="http://" && $tEight!="https://")
{
$url="http://".$url;
}
return $url;
}
You can use bellow function for any of youtube URL
I hope this will help you
function checkYoutubeId($id)
{
$youtube = "http://www.youtube.com/oembed?url=". $id ."&format=json";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
return json_decode($return, true);
}
This function return Youtube video detail if Id match to youtube video ID
A little improvement to #rvalvik answer would be to include the case of the mobile links (I've noticed it while working with a customer who used an iPad to navigate, copy and paste links). In this case, we have a m (mobile) letter instead of www. Regex then becomes:
#(https?://)?(?:www\.)?(?:m\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*#x
Hope it helps.
A slight improvement of another answer:
if (strpos($url, 'feature=youtu.be') === TRUE || strpos($url, 'youtu.be') === FALSE )
{
parse_str(parse_url($url, PHP_URL_QUERY), $id);
$id = $id['v'];
}
else
{
$id = basename($url);
}
This takes into account youtu.be still being in the URL, but not the URL itself (it does happen!) as it could be the referring feature link.
Other answers miss out on the point that some youtube links are part of a playlist and have a list paramater also which is required for embed code. So to extract the embed code from link one could try this JS code:
let urlEmbed = "https://www.youtube.com/watch?v=iGGolqb6gDE&list=PL2q4fbVm1Ik6DCzm9XZJbNwyHtHGclcEh&index=32"
let embedId = urlEmbed.split('v=')[1];
let parameterStringList = embedId.split('&');
if (parameterStringList.length > 1) {
embedId = parameterStringList[0];
let listString = parameterStringList.filter((parameterString) =>
parameterString.includes('list')
);
if (listString.length > 0) {
listString = listString[0].split('=')[1];
embedId = `${parameterStringList[0]}?${listString}`;
}
}
console.log(embedId)
Try it out here: https://jsfiddle.net/AMITKESARI2000/o62dwj7q/
try this :
$string = explode("=","http://www.youtube.com/watch?v=ZedLgAF9aEg");
echo $string[1];
would turn into: ZedLgAF9aEg
I have a .txt file where I would like to find an EXACT match of a single email entered in a form.
The present directives (see below) I used, work for a standard form. But when I use it in conjunction with an AJAX call and jQuery, it confirms it exists by just finding the first occurrence.
For example:
If that person enters "bobby#" it says not found, good.
If someone enters their full Email address and it exists in the file, it says "found", very good.
Now, if someone enters just "bobby", it says "found", not good.
I used the following three examples below with the same results.
if ( !preg_match("/\b{$email}\b/i", $emails )) {
echo "Sorry, not found";
}
and...
if ( !preg_match( "/(?:^|\W){$email}(?:\W|$)/", $emails )) {
echo "Sorry, not found";
}
and...
if ( !preg_match('/^'.$email.'$/', $emails )) {
echo "Sorry, not found";
}
my AJAX
$.ajax({
type: "POST",
url: "email_if_exist.php",
data: "email="+ usr,
success: function(msg){
my text file
Bobby Brown bobby#somewhere.com
Guy Slim guy#somewhere.com
Slim Jim slim#somewhere.com
I thought of using a jQuery function to only accept a full email address, but with no success partly because I didn't know where to put it in the script.
I've spent a lot of time in searching for a solution to this and I am now asking for some help.
Cheers.
Because your text file contains "bobby" in it, any regex such as you are suggesting will always find "bobby". I would suggest checking for the presence of the # symbol BEFORE you run the regex, as any valid email will always have # in it. Try something like this:
if (strpos($email,'#')) {
if ( !preg_match("/\b{$email}\b/i", $emails )) {
echo "Sorry, not found";
}
}
EDIT: Looking at this 4 years later... I would make the regex match to the end of the line, using the m modifier to specify multiline so the $ matches newline or EOF. The PHP line would be:
if ( !preg_match("/\b{$email}$/im", $emails )) {
If you're just checking to see if the user exists, this should work:
$users = trim(preg_replace('/\s\s+/', ' ', $users));
$userArray = explode(' ', $users);
$exists = in_array($email, $userArray);
Where $users is referencing to the example file and $email is referencing to the queried e-mail.
This replaces all newlines (and double spaces) with spaces and then splits by spaces into an array, then, if the e-mail exists in the array, the user exists.
Hope I helped!
'/^'.$email.'$/' is quite close. Since you want the check being "true" only if the full email address is on the file you should include in the pattern the "limits" of the email: Whitespace before and end_of_the_line after if:
'/ '.$email.'$/'
(Yes, I've just changed ^ -start of line- for a whitespace)
If your text file filled with lines that every line ending with the email,
so you can regex with testing and match by your "email + end od line"
like that:
if( preg_match("/.+{$email}[\n|\r\n|\r]/", $textFileEmails) )
{
/// code
}
The code would validate first using php core functions whether the email is correct or not and then check for the occurrence.
$email = 'bobby#somewhere.com';
$found = false;
//PHP has a built-in function to validate an email
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
//Grab lines from the file
$lines = file('myfile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
//Grab words from the line
$words = explode(" ", $line);
//If email found within the words set the flag as true.
if(in_array($email, $words)) {
$found = true;
//If the aim is only to find the email, we can break out here.
break;
}
}
}
if(false === $found) {
echo 'Not found!';
} else {
echo 'Found you!';
}
If you file is formatted as your example first_name, last_name, email#address.tdl
it's really easy to break it up on load to search.
I don't know why you would use preg_match for this bit your if you were advised to use preg use it to verify the email address. You're better off using indexOf method in php (strpos) to search the file but the below method works for your fixed file format.
Object Orientated File Reader and searcher
class Search{
private $users = array();
public function __construct($password_file){
$file = file_get_contents($password_file);
$lines = explode("\n", $file);
$users = array();
foreach($lines as $line){
$users = expode(" ", $line);
}
foreach($users as $user){
$this->users[] = array("first_name" => $user[0], "last_name" => $user[1], "email" => $user[2])
}
}
public function searchByEmail($email){
foreach($this->users as $key => $user){
if($user['email'] == $email){
// return user array
return $user;
// or you could return user id
//return $key;
}
}
return false;
}
}
Then to use
$search = new Search($passwdFile);
$user = $search->searchByEmail($_POST['email']);
echo ($user)? "found":"Sorry, not found";
Using preg_match to validate email then check
If you want to use preg and your own file search system.
function validateEmail($email) {
$v = "/[a-zA-Z0-9_-.+]+#[a-zA-Z0-9-]+.[a-zA-Z]+/";
return (bool)preg_match($v, $email);
}
then use like
if(validateEmail($_POST['email'])){
echo (strpos($_POST['email'], $emails) !== false)? "found":"Sorry, not found";
}