So far, I managed to find if ONE letter is in ANY given string. However, I cannot manage to ask for multiple conditions like 'a' && 'e' && 'i'... In a way that all of those letter need to be in the string so the echo "Vowel found" gets out.
I have tried with stristr, strpos... and so far my best guess was deprecated so I couldn't use it.
My last resource, which didn't work anyway, was to nest if conditions to make it work; also tried with arrays with no positive result.
$string = 'murcielago'; // a word with 5 vowels
if (stristr($string, 'a') == TRUE) {
echo 'Vowel found';
} else {
echo "Vowel not found";
}
This is my code for ONE string or letter to be found in the original given string.
It made me think further! Got it.
$string = "murcielago";
if (strpos($string,'a') && strpos($string,'e') && strpos($string,'i') && strpos($string,'o') && strpos($string,'u') == true)
{
echo "nailed it";
} else {
echo "No vowels for you";
}
ยดยดยด
I wonder if there is any way to make all the conditions into one since I am still using the same strpos function.
Try using a regex and preg_match
<?php
//Enter your code here, enjoy!
$string = 'murcielago';
// This will echo "vowel found"
if(preg_match( '`[aeiouy]`', $string)){
echo "vowel found\n";
}
$string2 = 'bcdfgplk';
// This won't echo anything
if(preg_match( '`[aeiouy]`', $string2 )){
echo "vowel not found\n";
}
Related
I have urls on my site like:
http://example.com/item/one/
http://example.com/item/two/
http://example.com/item/one/something
http://example.com/item/two/someotherthing
http://example.com/other/one/
http://example.com/other/two/
And I want to check the url and redirect if it matches /item/one/ or /item/two/ but NOT if it matches just /one/ or /two/, and NOT matching any string that goes deeper like something.
Ideally, I would want to match anything that contains both /item/ and one final path after that (ie /item/three/,/item/four/ as well).
What would be the best way to accomplish the match? preg_match (not sure how to write it for this)? explode?
UPDATE
Tried the following:
$thisurl = $_SERVER['REQUEST_URI'];
if (preg_match("/^\/item\/(.*)\/$/", $thisurl)) {
echo "it matches";
} else {
echo "nope nope nope";
}
Which works in this tester, but fails in my code (because it also matches true for things like:
http://example.com/item/one/something
http://example.com/item/two/someotherthing
which it should not.
This regex does the job:
~/item/[^/]+/$~i
Explanation:
~ : regex delimiter
/item/ : literally
[^/]+ : 1 or more character that is NOT a slash
/ : a slash
$ : end of string
~i : regex delimiter + case insensitive
In use:
$tests = array(
'http://example.com/item/one/',
'http://example.com/item/two/',
'http://example.com/item/one/something',
'http://example.com/item/two/someotherthing',
'http://example.com/other/one/',
'http://example.com/other/two/'
);
foreach($tests as $test) {
echo "$test --> ";
if (preg_match('~/item/[^/]+/$~i', $test)) {
echo "valid\n";
} else {
echo "invalid\n";
}
}
Output:
http://example.com/item/one/ --> valid
http://example.com/item/two/ --> valid
http://example.com/item/one/something --> invalid
http://example.com/item/two/someotherthing --> invalid
http://example.com/other/one/ --> invalid
http://example.com/other/two/ --> invalid
This is how you could do it using the explode function.
$url = [
'http://example.com/item/one/',
'http://example.com/item/two/',
'http://example.com/item/one/something',
'http://example.com/item/two/someotherthing',
'http://example.com/other/one/',
'http://example.com/other/two/'
];
foreach($url as $row){
$path = explode('/',str_replace('http://example.com/','',rtrim($row,'/')));
if(count($path) != 2){
continue;
}
if($path[0] != "item"){
continue;
}
if(in_array($path[1],[
'one',
'two'
])){
echo 'redirect...';
}
}
However a better answer would probably involve using some form of regex.
Finally got it working with this:
if (preg_match("/^\/item\/[-a-z]+\/$/", $thisurl)) { //matches any lowercase word that may or may not contain a dash
echo "it matches";
} else {
echo "nope nope nope";
}
DESPITE this page telling me that preg_match("/^\/item\/(.*)\/$/", $thisurl) would work, it did not.
I need to search inside a string to find if there ise any matches to this pattern:
class="%men%"
It means that the class may be equal to either:
class="men"
class="mainmen"
class="MyMen"
class="menSuper"
class="MyMenSuper"
etc
I need someting like strpos($string,'class="%men%') where % could be anything.
Best,
Martti
Try using preg_match
if (preg_match("/men/i", $class)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
Look at this link for more information http://www.php.net/preg_match
Edit :
So you can do like this (Inspired from the answer of Marius.C)
$string = '<div class="menlook">Some text</div>';
if (preg_match('/class="(.*)men(.*)"/i', $string)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
Store class "men" as string in variable like "$your_class"
then use preg_match like this:
if(preg_match('/men/i', $your_class)) {
echo "Men Class Found!";
}
ref: http://php.net/preg_match
or using strpos:
if(strpos(strtolower($your_class),'men')!==false) {
echo "Men Class Found!";
}
ref: http://www.w3schools.com/php/func_string_strpos.asp
Use strpos two times,
if(strpos($string,'class=') !== false && strpos($string,'men') !== false){
echo "true";
}
Note: strpos is much faster than preg_match.
This is possible without regular expressions which are quite slow
stristr($string, 'men')
I believe that you need something like this:
preg_match_all('/class="(.*)men(.*)"/i', $string, $matches);
How does know how I can make a PHP script that checks if a HTML code stored as a variable contain certain words?
To illustrate my problem:
$html = "<p>My name is Herman</p><br><span>I like to eat hamburgers</span>";
For example; I need a PHP script that can check if this variable contains "Herman" or "hamburger".
Thanks you :)
Use strpos.
<?php
$html = "<p>My name is Herman</p><br><span>I like to eat hamburgers</span>";
if(strpos($html, "Herman") !== false) {
echo "string found";
} else {
echo "string not found";
}
?>
You should probably use function strtolower to make your search case insensitive, then use strpos. It will find the numeric position of the first occurrence of your search in the haystack string return 0 if not found.
$lowhtml=strtolower($html);
if((strpos($lowhtml, 'hamburger')!=false) && (strpos($lowhtml, 'herman')!=false)){
echo "Contains";
}else{
echo "Doesn't contain";
}
So I get how to replace certain words with other ones. What I'm trying to figure out is how to take a word and replace it with a phrase and eliminate all other input.
For example:
bad word is 'dog'
user inputs -> 'You smell like a dog.'
instead of it replacing 'dog' with 'rainbow' or something, I want it to echo something like: 'You are a potty mouth'.
Here's what I have for code:
<?php
$find = array('dog', 'cat', 'bird');
$replace = 'You are a potty mouth.';
if (isset ($_POST['user_input'])&&!empty($_POST['user_input'])) {
$user_input = $_POST['user_input'];
$user_input_new = str_ireplace($find, $replace, $user_input);
echo $user_input_new;
}
?>
With this code it echos: 'You smell like a You are a pottymouth.'
I'm sure this is a repost and I apologize. Everything I've been able to find is documentation on how to replace only parts of strings, not entire ones.
Well, in this case you can just check whether there is a "bad word" in the user input string, and if it returns true, echo "You are a potty mouth."
You would want to use strpos()
e.g.
if( strpos($_POST['user_input'],'dog')!==FALSE ) {
echo('You are a potty mouth');
}
If you have an array of "bad words" you'll want to loop through them to check any occur within user input.
I've been looking at the same issue recently, here's a script I was working on to filter certain words. Still a work in progress but it has the ability to output the user message or a custom message. Hope it helps or points you in the right direction.
define("MIN_SAFE_WORD_LIMIT", 3);
$safe = true;
$whiteList = array();
$blackList = array();
$text = 'Test words fRom a piece of text.';
$blCount = count($blackList);
for($i=0; $i<$blCount; $i++) {
if((strlen($blackList[$i]) >= MIN_SAFE_WORD_LIMIT) && strstr(strtolower($text), strtolower($blackList[$i])) && !strstr(strtolower($text), strtolower($whiteList[$i]))) {
$safe = false;
}
}
if(!$safe) {
// Unsafe, flag for action
echo 'Unsafe';
} else {
echo $text;
}
You don't want to replace the bad words, but the whole string, so you should just match and if matched set the whole string to your replacement string.
Also, as pointed out in the comments the words can be part of another, valid, word so if you want to take that into account, you should match only whole words.
This simple example uses word boundaries in a regular expression to match your words (in the example this would be in a loop, looping over your bad words array):
foreach ($find as $your_word)
{
$search = '/\b' . preg_quote($your_word) . '\b/i';
if (preg_match($search, $_POST['user_input']) === 1)
{
// a match is found, echo or set it to a variable, whatever you need
echo $replace;
// break out of the loop
break;
}
}
Heres an alternative solution, match words and replace with * len of str. this wont match words like Scunthorpe as it uses word boundaries, Also you you can add a 3rd param to reveal the first letters of the word so you know what word was said without seeing it.
<?php
$badwords = array('*c word', '*f word','badword','stackoverflow');
function swear_filter($str,$badwords,$reveal=null) {
//Alternatively load from file
//$words = join("|", array_filter(array_map('preg_quote',array_map('trim', file('badwords.txt')))));
$words = join("|", array_filter(array_map('preg_quote',array_map('trim', $badwords))));
if($reveal !=null && is_numeric($reveal)){
return preg_replace("/\b($words)\b/uie", '"".substr("$1",0,'.$reveal.').str_repeat("*",strlen("$1")-'.$reveal.').""', $str);
}else{
return preg_replace("/\b($words)\b/uie", '"".str_repeat("*",strlen("$1")).""', $str);
}
}
$str="There was a naughty Peacock from Scunthorpe and it said a badword, on stackoverflow";
//There was a naughty Peacock from Scunthorpe and it said a b******, on s************
echo swear_filter($str,$badwords,1);
//There was a naughty Peacock from Scunthorpe and it said a *******, on *************
echo swear_filter($str,$badwords);
?>
Really quick noob question with php:
I'm trying to create a conditional statement where I can check if a variable partially matches a substring.
More specific in my case:
$cal is the name of a file, I want it so if $cal contains ".cfg" it echos some text.
pseudocode:
<?php if ($cal == "*.cfg")
{
echo "Hello ";
}
?>
if (strpos($cal, ".cfg") !== false)
{
echo "some text";
}
EDIT
My proposal for matching exactly "*.cfg":
$cal = "abc.cfgxyz";
$ext = "cfg";
if (strrpos($cal, ".".$ext) === strlen($cal)-strlen($ext)-1)
{
echo "matched";
}
In this case, you can simply look at the last four characters of $cal using substr:
if (substr($cal, -4) === '.cfg') {
echo "Hello ";
}
You should look into regular expressions for more complex problems.
if ( preg_match('/\\.cfg$/',$cal) ) echo "Hello ";
should to it. (Assuming you want to match the end of the input string, otherwise, leave out the $)
for simple patterns strpos will do nicely.
if (strpos ('.cfg', $string) !== false)
{
// etc
}
For more complicated parterns, you want preg_match, which can compare a string against a regular expression.
if (preg_match ('/.*?\.cfg/', $string))
{
// etc
}
The former offers better performance, but the latter is more flexible.
You can use various approaches here. For example:
$cal = explode('.', $cal);
if(last($cal) === "cfg")) {
echo "Hello";
}
Or using regular expressions (which are probably way slower than using strpos for example):
if(preg_match("/\.cfg$", $cal)) {
echo "Hello";
}
I honestly don't know how the explode() version compares to substr() with a negative value (lonesomeday's answer) or strpos() (which has its flaws, Frosty Z's answer). Probably the substr() version is the fastet, while regular expressions are the slowest possible way to do this).