I want to check the first word of some sentences. If the first word are For, And, Nor, But, Or, etc, I want to skip the sentence.
Here's the code :
<?php
$sentence = 'For me more';
$arr = explode(' ',trim($sentence));
if(stripos($arr[0],'for') or stripos($arr[0],'but') or stripos($arr[0],'it')){
//doing something
}
?>
Blank result, Whats wrong ? thank you :)
Here, stripos will return 0 if the word is found (found at position 0).
It returns false if the word is not found.
You should write :
if(stripos($arr[0],'for') !== false or stripos($arr[0],'but') !== false or stripos($arr[0],'it') !== false){
//skip
}
Stripos returns the position on the first occurrence of the needle in the haystack
The first occurrence is at position 0, which evaluates to false.
Try this as an alternative
$sentence = 'For me more';
// make all words lowercase
$arr = explode(' ', strtolower(trim($sentence)));
if(in_array($arr[0], array('for', 'but', 'it'))) {
//doing something
echo "found: $sentence";
} else {
echo 'failed';
}
Perhaps use preg_filter if you are going to know what the string to be evaluated is (i.e. you don't need to parse out sentences).
$filter_array = array(
'/^for\s/i',
'/^and\s/i',
'/^nor\s/i',
// etc.
}
$sentence = 'For me more';
$result = preg_filter(trim($sentence), '', $filter_array);
if ($result === null) {
// this sentence did not match the filters
}
This allows you to determine a set of filter regex patterns to see if you have a match. Note that in this case I just used '' as "replacement" value, as you don't really care about actually making a replacement, this function just gives you a nice way to pas in an array of regular expressions.
Related
I am doing text analysis. I have a table having positive words.The records are being fetched one by one and imploded in an array through mysqli_fetch_array.
while(($rowx = mysqli_fetch_array($resultx,MYSQLI_NUM)))
{
$wordx = implode("", $rowx);
if(strpos($text, $wordx) !== FALSE)
{
$count1 = substr_count($text, $wordx);
$pos_prob += .2 * $count1;
echo "pos prob is".$pos_prob;
}
}
But strpos is not able to match the string that is being fetched from the table.i.e. if text is "It's an excellent book" the if condition is never true. Even though the word excellent is present in the table. And if I hard code the value $wordx as
$wordx='excellent';
Only then it works. Does anyone has any idea why this is happening? :( Any help would be much appreciated :)
I don't understand the need to implode each row. My assumption is that each row has one word.
Simple strpos text matching example:
<?php
$words = array(
'big',
'fat',
'mamma'
);
$text = 'One day fat foo walked to the bar';
$matches = array();
foreach($words as $word) {
if(strpos($text, $word) !== false)
$matches[] = $word;
}
var_dump($matches);
Output:
array (size=1)
0 => string 'fat' (length=3)
Note that this would also match word parts and be case sensitive, so not ideal. For example: 'fat' is contained in the words: 'father', 'infatuated' and 'marrowfat'.
Sorry, a bit new to php. Have tried all I know, but failed and seeking expert help.
I have a string similar to this..
/%mydocs%/%myfolder%/%date%/%filename%.html
Basically the %vars% represents different strings and seperated by /, like a URL.
I need to find %date% (or any given variable) if it's present and it's position in the string, like it's at position 3 in the example above.
I tried this,
$date = preg_match( '%date%', '/%mydocs%/%myfolder%/%date%/%filename%.html');
But it's neither returning anything nor the position.
Any help, even some heads up to play with, will be appriciated.
strpos
<?php
$mystring = '/%mydocs%/%myfolder%/%date%/%filename%.html';
$findme = '%date%';
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
Result:
The string '%date%' was found in the string '/%mydocs%/%myfolder%/%date%/%filename%.html' and exists at position 21
How about using preg_split:
$var = '%date%';
$str = '/%mydocs%/%myfolder%/%date%/%filename%.html';
$list = preg_split('#/#', $str, -1, PREG_SPLIT_NO_EMPTY);
for($i=0; $i<count($list); $i++) {
if ($list[$i] == $var) {
echo "Found $var at position ",$i+1,"\n";
}
}
output:
Found %date% at position 3
preg_match returns a boolean for whether there was a match or not, but you can pass a third parameter - $matches, which will contain the matches according to the regular expression provided.
You don't look to be using a regular expressions - for what you are doing you probably want to look at strpos instead. http://uk3.php.net/strpos
How do I find exact 2, in a string using strpos? Is it possible using strpos? The example below returns "Found" even though the match is NOT exact to what I need. I understand 2, is matching with 22,. It should return "Not Found". I am matching ID's in this example.
$string = "21,22,23,26,";
$find = "2,";
$pos = strpos($string, $find);
if ($pos !== false) {
echo "Found";
} else {
echo "Not Found";
}
Unless the string is enormous, make an array and search it:
$string = "21,22,23,26,";
$arr = explode(",", $string);
// array_search() returns its position in the array
echo array_search("2", $arr);
// null output, 2 wasn't found
Actually, in_array() is probably faster:
// in_array() returns a boolean indicating whether it is found or not
var_dump(in_array("2", $arr));
// bool(false), 2 wasn't found
var_dump(in_array("22", $arr));
// bool(true), 22 was found
This will work as long as your string is a comma-delimited list of values. If the string is really long, making an array may be wasteful of memory. Use a string manipulation solution instead.
Addendum
You didn't specify, but if by some chance these strings came from a database table, I would just add that the appropriate course of action would be to properly normalize it into another table with one row per id rather than store them as a delimited string.
Try with explode and in_array
Example:
$string = "21,22,23,26,";
$string_numbers = explode(",", $string);
$find = 2;
if (in_array($find, $string_numbers)) {
echo "Found";
} else {
echo "Not Found";
}
You can use preg_match if you want to avoid arrays.
$string = "21,22,23,26,";
$find = '2';
$pattern = "/(^$find,|,$find,|,$find$)/";
if (0 === preg_match($pattern, $string)) {
echo "Not Found";
} else {
echo "Found";
}
This will find your id at beginning, middle or at the end of the string. Of course, I am assuming $string does not contain characters other than numbers and commas (like spaces).
I'm trying to find out if a string matches any of my bad words in my array IE:
$badWords = Array('bad', 'words', 'go', 'here');
$strToCheck = "checking this string if any of the bad words appear";
if (strpos($strToCheck, $badWords)) {
// bad word found
}
the issue is strpos can only check for a string and not an array, is there a method of doing this without looping through the array of badwords?
Not exactly, since all solutions inevitably must loop over your array, even if it's "behind the scenes". You can make a regular expression out of $badWords, but the runtime complexity will probably not be affected. Anyway, here's my regex suggestion:
$badWordsEscaped = array_map('preg_quote', $badWords);
$regex = '/'.implode('|', $badWordsEscaped).'/';
if(preg_match($regex, $strToCheck)) {
//bad word found
}
Note that I've escaped the words to protect against regex-injections, if they contain any special regex characters such as / or .
array_intersect() gives you the list of matching words:
if (count(array_intersect(preg_split('/\s+/', $strToCheck), $badWords))) {
// ...
}
in_array.
Read question wrong.
Simplest implementation is to call strpos() for each of the badwords:
<?php
$ok = TRUE;
foreach($badwords AS $word)
{
if( strpos($strToCheck, $word) )
{
$ok = FALSE;
break;
}
}
?>
Try This..
$badWords = array('hello','bad', 'words', 'go', 'here');
$strToCheck = 'i am string to check and see if i can find any bad words here';
//Convert String to an array
$strToCheck = explode(' ',$strToCheck);
foreach($badWords as $bad) {
if(in_array($bad, $strToCheck)) {
echo $bad.'<br/>';
}
}
the above code will return all matched bad words, you can further extend it to implement your own logic like replacing the bad words etc.
I need a simple word filter that will kill a script if it detects a filtered word in a string.
say my words are as below
$showstopper = array(badword1, badword2, badword3, badword4);
$yourmouth = "im gonna badword3 you up";
if(something($yourmouth, $showstopper)){
//stop the show
}
You could implode the array of badwords into a regular expression, and see if it matches against the haystack. Or you could simply cycle through the array, and check each word individually.
From the comments:
$re = "/(" . implode("|", $showstopper) . ")/"; // '/(badword1|badword2)/'
if (preg_match($re, $yourmouth) > 0) { die("foulmouth"); }
in_array() is your friend
$yourmouth_array = explode(' ',$yourmouth);
foreach($yourmouth_array as $key=>$w){
if (in_array($w,$showstopper){
// stop the show, like, replace that element with '***'
$yourmouth_array[$key]= '***';
}
}
$yourmouth = implode(' ',$yourmouth_array);
You might want to benchmark this vs the foreach and preg_match approaches.
$showstopper = array('badword1', 'badword2', 'badword3', 'badword4');
$yourmouth = "im gonna badword3 you up";
$check = str_replace($showstopper, '****', $yourmouth, $count);
if($count > 0) {
//stop the show
}
A fast solution involves checking the key as this does not need to iterate over the array. It would require a modification of your bad words list, however.
$showstopper = array('badword1' => 1, 'badword2' => 1, 'badword3' => 1, 'badword4' => 1);
$yourmouth = "im gonna badword3 you up";
// split words on space
$words = explode(' ', $yourmouth);
foreach($words as $word) {
// filter extraneous characters out of the word
$word = preg_replace('/[^A-Za-z0-9]*/', '', $word);
// check for bad word match
if (isset($showstopper[$word])) {
die('game over');
}
}
The preg_replace ensures users don't abuse your filter by typing something like bad_word3. It also ensures the array key check doesn't bomb.
not sure why you would need to do this but heres a way to check and get the bad words that were used
$showstopper = array(badword1, badword2, badword3, badword4);
$yourmouth = "im gonna badword3 you up badword1";
function badWordCheck( $var ) {
global $yourmouth;
if (strpos($yourmouth, $var)) {
return true;
}
}
print_r(array_filter($showstopper, 'badWordCheck'));
array_filter() returns an array of bad words, so if the count() of it is 0 nothign bad was said