In php, how can I check if a string has no characters at all.
Currently I do like below, and replace - with ' '. But if a search string contained all bad words, it'll leave me with ' '(3 blank spaces). The length will still show as 3 and it'll head off to the sql processor. Any method to check if a string has no characters or numbers at all?
$fetch = false;
#$strFromSearchBox = 'Why-you-foo-bar-I-ought-to-tar-you';
$strFromSearchBox = 'foo-bar-tar';
if(strlen($strFromSearchBox) >=2)
{
$newString = str_replace($theseWords,'',$strFromSearchBox);
$newString = str_replace('-',' ',$newString);
if(strlen($newString)>=2)
{
$fetch = true;
echo $newString;
}
}
if($fetch){echo 'True';}else{echo 'False';}
$fetch = false;
#$strFromSearchBox = 'Why-you-foo-bar-I-ought-to-tar-you';
$strFromSearchBox = 'foo-bar-tar';
if(strlen($strFromSearchBox) >=2)
{
$newString = str_replace($theseWords,'',$strFromSearchBox);
$newString = str_replace('-',' ',$newString);
$newString=trim($newString); //This will make the string 0 length if all are spaces
if(strlen($newString)>=2)
{
$fetch = true;
echo $newString;
}
}
if($fetch){echo 'True';}else{echo 'False';}
If you strip the leading and backmost spaces, the length will go down to 0 which you can easily turn into the $fetch boolean:
$fetch = (bool) strlen(trim($newString));
See trimDocs.
Use regex perhaps...
if (preg_match('/[^A-Za-z0-9]+/', $strFromSearchBox))
{
//is true that $strFromSearchBox contains letters and/or numbers
}
Related
I am looking for a way to detect and drop quotes with in quotes, for example: something "something "something something" something" something.
In the above example the italic something something is wrapped in double-quotes as you can see. I want to strip the string inside from these outer quotes.
So, the expression should simply look for quotes with a text between them plus a another set of text-wrapping text, and then drop the quotes wrapping the last.
This is my current code (php):
preg_match_all('/".*(".*").*"/', $text, $matches);
if(is_array($matches[0])){
foreach($matches[0] as $match){
$text = str_replace($match, '"' . str_replace('"', '', $match) . '"', $text);
}
}
If the string starts with a " and the double quotes inside the string are always balanced you might use:
^"(*SKIP)(*F)|"([^"]*)"
That would match a double quote at the start of the string and then skips that match using SKIP FAIL. Then it would match ", capture in a group what is between the " and match a " again.
In the replacement you could use capturing group 1 $1
$pattern = '/^"(*SKIP)(*F)|"([^"]+)"/';
$str = "\"something \"something something\" and then \"something\" something\"";
echo preg_replace($pattern, "$1", $str);
"something something something and then something something"
Demo
You could leverage strpos() with the third parameter (offset) to look up all quotes and replace every quote from 1 to n-1:
<?php
$data = <<<DATA
something "something "something something" something" something
DATA;
# set up the needed variables
$needle = '"';
$lastPos = 0;
$positions = array();
# find all quotes
while (($lastPos = strpos($data, $needle, $lastPos)) !== false) {
$positions[] = $lastPos;
$lastPos = $lastPos + strlen($needle);
}
# replace them if there are more than 2
if (count($positions) > 2) {
for ($i=1;$i<count($positions)-1;$i++) {
$data[$positions[$i]] = "";
}
}
# check the result
echo $data;
?>
This yields
something "something something something something" something
You could even hide it in a class:
class unquote {
# set up the needed variables
var $data = "";
var $needle = "";
var $positions = array();
function cleanData($string="", $needle = '"') {
$this->data = $string;
$this->needle = $needle;
$this->searchPositions();
$this->replace();
return $this->data;
}
private function searchPositions() {
$lastPos = 0;
# find all quotes
while (($lastPos = strpos($this->data, $this->needle, $lastPos)) !== false) {
$this->positions[] = $lastPos;
$lastPos = $lastPos + strlen($this->needle);
}
}
private function replace() {
# replace them if there are more than 2
if (count($this->positions) > 2) {
for ($i=1;$i<count($this->positions)-1;$i++) {
$this->data[$this->positions[$i]] = "";
}
}
}
}
And call it with
$q = new unquote();
$data = $q->cleanData($data);
Objective: strings with ' should match the string without it.
Example:
$first_string = "alex ern o'brian";
$second_string = "alex-ern o brian";
$pattern = array("/(-|\.| )/", "/(')/");
$replace = array(' ', '(\s|)');
$first_string = preg_replace($pattern, $replace, $first_string);
$second_string = preg_replace($pattern, $replace, $second_string);
$first_string_split = preg_split("/(-|\.| )/", $first_string);
$first_string_split[] = $first_string;
$second_string_split = preg_split("/(-|\.| )/", $second_string);
$second_string_split[] = $second_string;
$first_string = array_slice($first_string_split, -1)[0];
$second_string = array_slice($second_string_split, -1)[0];
if(in_array($first_string, $second_string_split) || in_array($second_string, $first_string_split))
{
echo 'true';
} else {
echo 'false';
}
I think you are expecting this.
Solution 1: Try this code snippet here
Regex: (\s|) this will match either space or null.
<?php
ini_set('display_errors', 1);
$string = "o'brian";
$string=str_replace("'", "(\s|)",$string);
$list = array("o'neal", "o brian", "obrian");
$result=array();
foreach($list as $value)
{
if(preg_match("/$string/", $value))
{
$result[]=$value;
}
}
print_r($result);
Solution 2:
Regex: [a-z]+ will match character from a to z.
$string1="o brian";
$string2="obrian";
if(preg_match("/".implode(" ", $matches[0])."/", $string1))
{
echo "matched";
}
if( preg_match("/".implode("", $matches[0])."/", $string2))
{
echo "matched";
}
I'm not sure if I got your question right, but this should do it:
(?<=\w)'(?=\w)
It matches every ' character, which is followed and preceded by a word character. The word character \w is equal to [a-zA-Z0-9_].
Here is a live example to test the regex
Here is a live PHP example
I'm trying to develop a PHP application where it takes comments from users and then match the string to check if the comment is positive or negative. I have list of negative words in negative.txt file. If a word is matched from the word list, then I want a simple integer counter to increment by 1. I tried the some links and created the a code to check if the comment has is negative or positive but it is only matching the last word of the file.Here's the code what i have done.
<?php
function teststringforbadwords($comment)
{
$file="BadWords.txt";
$fopen = fopen($file, "r");
$fread = fread($fopen,filesize("$file"));
fclose($fopen);
$newline_ele = "\n";
$data_split = explode($newline_ele, $fread);
$new_tab = "\t";
$outoutArr = array();
//process uploaded file data and push in output array
foreach ($data_split as $string)
{
$row = explode($new_tab, $string);
if(isset($row['0']) && $row['0'] != ""){
$outoutArr[] = trim($row['0']," ");
}
}
//---------------------------------------------------------------
foreach($outoutArr as $word) {
if(stristr($comment,$word)){
return false;
}
}
return true;
}
if(isset($_REQUEST["submit"]))
{
$comments = $_REQUEST["comments"];
if (teststringforbadwords($comments))
{
echo 'string is clean';
}
else
{
echo 'string contains banned words';
}
}
?>
Link Tried : Check a string for bad words?
I added the strtolower function around both your $comments and your input from the file. That way if someone spells STUPID, instead of stupid, the code will still detect the bad word.
I also added trim to remove unnecessary and disruptive whitespace (like newline).
Finally, I changed the way how you check the words. I used a preg_match to split about all whitespace so we are checking only full words and don't accidentally ban incorrect strings.
<?php
function teststringforbadwords($comment)
{
$comment = strtolower($comment);
$file="BadWords.txt";
$fopen = fopen($file, "r");
$fread = strtolower(fread($fopen,filesize("$file")));
fclose($fopen);
$newline_ele = "\n";
$data_split = explode($newline_ele, $fread);
$new_tab = "\t";
$outoutArr = array();
//process uploaded file data and push in output array
foreach ($data_split as $bannedWord)
{
foreach (preg_split('/\s+/',$comment) as $commentWord) {
if (trim($bannedWord) === trim($commentWord)) {
return false;
}
}
}
return true;
}
1) Your storing $row['0'] only why not others index words. So problem is your ignoring some of word in text file.
Some suggestion
1) Insert the text in text file one by one i.e new line like this so you can access easily explode by newline to avoiding multiple explode and loop.
Example: sss.txt
...
bad
stupid
...
...
2) Apply trim and lowercase function to both comment and bad string.
Hope it will work as expected
function teststringforbadwords($comment)
{
$file="sss.txt";
$fopen = fopen($file, "r");
$fread = fread($fopen,filesize("$file"));
fclose($fopen);
foreach(explode("\n",$fread) as $word)
{
if(stristr(strtolower(trim($comment)),strtolower(trim($word))))
{
return false;
}
}
return true;
}
I need to find out if there are any redundant words in string or not .Is there any function that can provide me result in true/false.
Example:
$str = "Hey! How are you";
$result = redundant($str);
echo $result ; //result should be 0 or false
But for :
$str = "Hey! How are are you";
$result = redundant($str);
echo $result ; //result should be 1 or true
Thank you
You could use explode to generate an array containing all words in your string:
$array = explode(" ", $str);
Than you could prove if the arrays contains duplicates with the function provided in this answer:
https://stackoverflow.com/a/3145660/5420511
I think this is what you are trying to do, this splits on punctuation marks or whitespaces. The commented out lines can be used if you want the duplicated words:
$str = "Hey! How are are you?";
$output = redundant($str);
echo $output;
function redundant($string){
$words = preg_split('/[[:punct:]\s]+/', $string);
if(max(array_count_values($words)) > 1) {
return 1;
} else {
return 0;
}
//foreach(array_count_values($words) as $word => $count) {
// if($count > 1) {
// echo '"' . $word . '" is in the string more than once';
// }
//}
}
References:
http://php.net/manual/en/function.array-count-values.php
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.preg-split.php
Regex Demo: https://regex101.com/r/iH0eA6/1
Say I have string such as below:
"b<a=2<sup>2</sup>"
Actually its a formula. I need to display this formula on webpage but after b string is hiding because its considered as broken anchor tag. I tried with htmlspecialchars method but it returns complete string as plain text. I am trying with some regex but I can get only text between some tags.
UPDATE:
This seems to work with this formula:
"(c<a) = (b<a) = 2<sup>2</sup>"
And even with this formula:
"b<a=2<sup>2</sup>"
HERE'S THE MAGIC:
<?php
$_string = "b<a=2<sup>2</sup>";
$string = "(c<a) = (b<a) = 2<sup>2</sup>";
$open_sup = strpos($string,"<sup>");
$close_sup = strpos($string,"</sup>");
$chars_array = str_split($string);
foreach($chars_array as $index => $char)
{
if($index != $open_sup && $index != $close_sup)
{
if($char == "<")
{
echo "<";
}
else{
echo $char;
}
}
else{
echo $char;
}
}
OLD SOLUTION (DOESN'T WORK)
Maybe this can help:
I've tried to backslash chars, but it doesn't work as expected.
Then i've tried this one:
<?php
$string = "b<a=2<sup>2</sup>";
echo $string;
?>
Using < html entity it seems to work if i understood your problem...
Let me know
Probably you can give spaces such as :
b < a = 2<sup>2</sup>
It does not disappear the tag and looks much more understanding....
You could try this regex approach, which should skip elements.
$regex = '/<(.*?)\h*.*>.+<\/\1>(*SKIP)(*FAIL)|(<|>)/';
$string = 'b<a=2<sup>2</sup>';
$string = preg_replace_callback($regex, function($match) {
return htmlentities($match[2]);
}, $string);
echo $string;
Output:
b<a=2<sup>2</sup>
PHP Demo: https://eval.in/507605
Regex101: https://regex101.com/r/kD0iM0/1