I have a sample code to check if the string subdomain is "us"
$string = "www.domain.com"; // 1
$string = "domain.com"; // 2
$string = "us.domain.com"; // 3
$string = "www.us.domain.com"; // 4
if (preg_match("/^(?=.{2})[a-z0-9]+(?:-[a-z0-9]+)*$/i", $_SERVER['SERVER_NAME'])) {
echo "$string include us";
} else {
echo "$string not include us";
}
But result error, how to fix it
If by "subdomain" you mean that the tld and the main domain are excluded, that means we'll have to check for the text "us" and two dots further in the text.
It will also match with sub-subdomains (Like us.subdomain.domain.us)
<?php
$domains = [
'www.domain.us',
'domain.us',
'domainuscomputers.com',
'us.domain.us',
'www.asuscomputers.usdomain.us',
'us.subdomain.domain.us',
];
$reg = '/us.*\..*\./';
foreach ($domains as $domain) {
$match = preg_match($reg, $domain) ? 'subdomain containing "us" found' : 'No match';
printf('domain %s : %s<br>', $domain, $match);
}
Note that the regular expression may be improved, but hey, it works !
In this specific case I don't see the need of using regular expressions.
I think a simple strpos will do the job.
Try this code:
$string = "www.domain.com"; // 1
$string = "domain.com"; // 2
$string = "us.domain.com"; // 3
$string = "www.us.domain.com"; // 4
if (strpos($string,'us.')) {
echo "$string include us";
} else {
echo "$string not include us";
}
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.
i am trying to determine the best way to determine whether an email address is an outlook or hotmail address.
i therefore need to collect the values after the #
i.e
testemail#outlook.com
caputure the #
however this will not work in all instance as
this email address is valid:
"foo\#bar"#iana.org
i read that a solution could be to explode it, i.e:
$string = "user#domain.com";
$explode = explode("#",$string);
array_pop($explode);
$newstring = join('#', $explode);
echo $newstring;
this solution seems bit long and only captures the first values
would really appreciate some help
if You explode This :
$string = "user#domain.com";
$explode = explode("#",$string);
it Will be :
$explode[0] = user
$explode[1] = domain.com
try to use array_reverse() ti pick the last value of email:
<?php
$email='exa#mple#hotmail.com';
$explode_email=explode('#',$email);
$reversed_array=array_reverse($explode_email);
$mailserver=explode('.',$reversed_array[0]);
echo $mailserver[0];
?>
You could always just keep it simple and test if either value exists in the string using strpos() or stripos().
if ( FALSE !== stripos($string, 'outlook') {
// outlook exists in the string
}
if ( FALSE !== stripos($string, 'hotmail') {
// hotmail exists in the string
}
I hope this will be easy for you to understand.
<?php
$emailAddress = 'mailbox#hotmail.com'; //Email Address
$emailStringArray = explode('#',$emailAddress); // take apart the email string.
$host = $emailStringArray[1]; //last string after # . $emailStringArray[0] = Mailbox & $emailStringArray[1] = host
if($host == "hotmail.com" || $host == "outlook.com"){
//matches to outlook.com or hotmail.com
}
else{
//Does not match to outlook.com or hotmail.com
}
I would recommend matching with a regular expression.
if (preg_match("/\#hotmail.com$/", $email)) {
echo "on hotmail";
} else if (preg_match("/\#outlook.com$/", $email)) {
echo "on outlook";
} else {
echo "different domain";
}
Additionally, if you want to capture full domain to variable, you can do it like this:
$matches = [];
if (preg_match("/^.*\#([\w\.]+)$/", $email, $matches)) {
echo "Domain: " . $matches[1];
} else {
echo "not a valid email address.";
}
Try this :
$emailAddress = 'example\#sometext\#someothertext#hotmail.com';
$explodedEmail = explode('#', $emailAddress);
$emailServerHostName = end($explodedEmail);
$emailServerNameExploded = explode('.', $emailServerHostName);
$emailServerName = $emailServerNameExploded[0];
echo $emailServerName;
I want to replace some numbers in a string with the content of the array in the position which this number points to.
For example, replace "Hello 1 you are great", with "Hello myarray[1] you are great"
I was doing the next: preg_replace('/(\d+)/','VALUE: ' . $array[$1],$string);
But it does not work. How could I do it?
You should use a callback.
<?php
$str = 'Hello, 1!';
$replacements = array(
1 => 'world'
);
$str = preg_replace_callback('/(\d+)/', function($matches) use($replacements) {
if (array_key_exists($matches[0], $replacements)) {
return $replacements[$matches[0]];
} else {
return $matches[0];
}
}, $str);
var_dump($str); // 'Hello, world!'
Since you are using a callback, in the event that you actually want to use a number, you might want to encode your strings as {1} or something instead of 1. You can use a modified match pattern:
<?php
// added braces to match
$str = 'Hello, {1}!';
$replacements = array(
1 => 'world'
);
// added braces to regex
$str = preg_replace_callback('/\{(\d+)\}/', function($matches) use($replacements) {
if (array_key_exists($matches[1], $replacements)) {
return $replacements[$matches[1]];
} else {
// leave string as-is, with braces
return $matches[0];
}
}, $str);
var_dump($str); // 'Hello, world!'
However, if you are always matching known strings, you may want to use #ChrisCooney's solution because it offers less opportunity to screw up the logic.
The other answer is perfectly fine. I managed it this way:
$val = "Chris is 0";
// Initialise with index.
$adj = array("Fun", "Awesome", "Stupid");
// Create array of replacements.
$pattern = '!\d+!';
// Create regular expression.
preg_match($pattern, $val, $matches);
// Get matches with the regular expression.
echo preg_replace($pattern, $adj[$matches[0]], $val);
// Replace number with first match found.
Just offering another solution to the problem :)
$string = "Hello 1 you are great";
$replacements = array(1 => 'I think');
preg_match('/\s(\d)\s/', $string, $matches);
foreach($matches as $key => $match) {
// skip full pattern match
if(!$key) {
continue;
}
$string = str_replace($match, $replacements[$match], $string);
}
<?php
$array = array( 2 => '**', 3 => '***');
$string = 'lets test for number 2 and see 3 the result';
echo preg_replace_callback('/(\d+)/', 'replaceNumber', $string);
function replaceNumber($matches){
global $array;
return $array[$matches[0]];
}
?>
output
lets test for number ** and see *** the result
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.
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
}