PHP- Search for string in an array, in a loop - php

What I would like to do is search a file containing; multiple space delimited words and characters, on multiple lines, using preg_grep, containing a certain string, and store as a variable. I would like to then "for loop" through those matched lines, and search within for yet another string.
For sake of example, assume $c contains all the lines that match variable $a (in an Array?), in the file $o, and returns 9 lines that contain that variable. How
$c = preg_grep("/\b$a\b/", $o);
So I set $max = sizeof($c)
$max = sizeof($c); // In this example contains 9
Here I try to loop through $c to find variable $b, and would like to print that line that matches
for ($i = 0; $i < $max; $i++) {
$st = preg_grep("/\b$b\b/", $c);
echo implode($st, ' ');
}
In the first search if I echo implode($c, ' '), I get all 9 values displayed as one solid string. It seems though using the same technique after my loop, I am not getting the result I want, which is a single line resulting from matching both variables.
Additionally, I know there may be much easier ways to accomplish this, but following this example, Where am I making a mistake(s).
EDIT
If it helps, a sample of the text file:
13 04000 Atlanta city GA 394017 +33.762900 -08.4422592
13 56000 North Atlanta CDP PA 27812 0000000147 +33.862550
Where $c = preg_grep("/\b$a\b/", $o); would match both lines
And ideally, if $b= PA, the second preg_grep would yeild:
13 56000 North Atlanta CDP PA 27812 0000000147 +33.862550

Assuming $o is an array of lines:
$result = preg_grep("/\b$b\b/", preg_grep("/\b$a\b/", $o));
echo implode(" ", $result);
This will give an array of elements from $o that match both $a and $b.

Related

I want to turn an array $badwords into a file to be called

I have a form that sends an email. I have a list of words to ban, and they are manually entered in an array. Each word in the array gets a point which eventually can reject a mail send. I want to put the words into a file instead to call up because though this works, its slow to update especially across several domains. Sorry for my lack of skill. Thanks.
$badwords = array("word1", "word2", "word3");
foreach ($badwords as $word)
if (strpos(strtolower($_POST['comments']), $word) !== false
As the badwords add up, the point value increase to a limit which then rejects the send.
Excuse me, I was not clear evidently. I want to take the EXISTING array of badwords and put them in a file, in some sort of order and entry (line per line, or comma separated?). I want to call that file to be read by the existing script.
So maybe it theoretically looks like :
$badwords = badwords.php and so on....
Thanks
I'm not sure if that's what you need? Try it.
This code should solve what you need. Find 'badwords' from the 'bedwords' list in the 'message', calculate the occurrence of word each of the 'bedwords' and add 1 penalty point to the '$ penalty' for each positive result (even duplicate).
the code ignores uppercase and lowercase letters.
Set the list:
$badwords = ['world', 'car', 'cat', 'train',];
$message = "World is small. I love music and my car. But I also love to
travel by train. I like animals, especially my cat.";
We will initialize the variable for counting penalty points.
$penalty = 0;
Now we need to go through the 'message' as many as there are in the 'badwords' fields. We will use the 'for' loop.
for($k =0; $k <= count($badwords) - 1; $k++):
preg_match_all("/$badwords[$k]/i", $message, $out[])
endfor;
We have now passed a total of 5 (from 0 to 4) through the message loop. Using a regular expression, we store word matches in an 'out' array, creating a multidimensional array. Now you need to go through this "out" field. We reduce its dimensions.
foreach ($out as &$value):
$value = $value[0];
endforeach;
We will now go through this out field again using the 'for' loop and calculate the number of values in each dimension. Based on the calculated values we will assign 1 penalty point for each match and a duplicate.
for($n = 0; $n <= count($out)-1; $n++):
$penalty += count($out[$n]);
endfor;
The result is the number of points awarded.
Here is source of the php, on PHP Fiddle
http://phpfiddle.org/main/code/jzyw-hva6
In words.php:
<?php
$words = ["filter","these","words","out"];
In your main script:
<?php
include "words.php";
print_r($words);
Result:
Array
(
[0] => filter
[1] => these
[2] => words
[3] => out
)
figured it out.
in the root of my webspace I made a file called words.php
<?php
$badwords = array("000", "adult", etc
then added an include (as there are counted words, so can be more than one) to my main file
include "../badwords.php"; // the array list was here
and on to the foreach statement.
and removed this original line from that main file.
$badwords = array("word1", "word2", "word3");
Seems to be working. Thanks

how to read a substring as a whole

This was difficult to put into a title.
Essentially what I want to do is, when I get some random binary code i need certain number patterns be converted into a declared symbol.
For example :
input: 11100011111
Output: ABF
So essentially
111 = A, 000 = B, 11111 = C, 1111 = D
Note!That the output has to correspond in order so if it started with 111 the output hast to start with A(declared symbol for said pattern).
There's a D there also essentially the first four characters of C is the same as D but it must output the one most similar.
First i tried to put this into a for loop
so, check string characters, if there's a 1 echo one and vice versa
for ($i=0; $i < $getInput[$i] ; $i++) {
if ($getInput[$i] == 1) {
echo "ONE";
} elseif ($getInput[$i] == 0) {
echo "ZERO";
}
}
this was just for testing, essentially in this theory i can check if if there is a consecutive pattern so 000 it will refer to an array with different patterns already assigned and then output the symbol whatever was assigned to that pattern.
I also tried using foreaches but due to inexperience...
I did some research and found this topic:
How do I check if a string contains a specific word?
which kinda helped since with this code
$a = '1110001111';
if (strpos($a, '1111') !== false) {
echo 'D';
}
It outputs the character in right order, problem with this approach is that well it kinda means id need to write out if statements repetitively, and secondly if there were to be 1111 in the input, it would take the part 111 and 1111 as two different strings and output both of them
EDIT:
Essentially what i just thought is, i actually need to compare 4 digits to different patterns, i can put the string into an array split it into 4's and then compare with another array which holds the declared patterns (1111 = a etc..), so in a 4 digit binary 0000 there can be about 17 different patterns therefor no need for anything above >4
Then again if there were an odd number of 1's and 0's there'd be some left off.
Then these should just be outputted as is. so if there were 1010110 = A110 since A is declared as a pattern of 1010
You can use str_split to split the string in chunkes of four digits.
Then I use an associative array with replacements.
I loop the match array and echo replacement character.
$str = "111000111111";
//preg_match_all('/(.)\1*/', $str, $match);
$digits = str_split($str, 4);
$replace = array("1110" => "A", "0011" => "B", "1111" => "C");
Foreach($digits as $val){
Echo $replace[$val];
}
https://3v4l.org/QfQQ8
This code will give you an array of the 4 digits and then you can parse that via a foreach and lookup.
<?php
$string = "11111001011100001111";
$matches = [];
preg_match_all("/[1|0]{4}/", $string, $matches);
echo "<pre>";
print_r($matches);
Which the output of that would be:
<pre>Array
(
[0] => Array
(
[0] => 1111
[1] => 1001
[2] => 0111
[3] => 0000
[4] => 1111
)
)

i want to compare the string and show to characters which match in both strings in php

i want to compare the string and show to characters which match in both strings in php i tried everything but failed to do this please give me any idea how to do this in php
e.g i have two variables
I have to compare $a and $b and give the output as letters whicj are common in both
$a="hello ";
$b= "hell";
output should be : :: hell as first 4 character matches so it should show hell please help me to do this
i have tried everything almost everything which i know or could i find on web
What I tried.. I spit the strings to array... Using nested for loop to find the non matched letters... I wrote code more than 35 lines.. But no result :( Please help me ......
In your case, it would be enough to use array_intersect and str_split functions to get characters common to both input strings(of course, if order of characters doesn't matter):
$a = "hello ";
$b = "hell";
$common = array_intersect(str_split(trim($a)), str_split(trim($b)));
print_r($common);
The output:
Array
(
[0] => h
[1] => e
[2] => l
[3] => l
)
http://php.net/manual/en/function.array-intersect.php
This PHP code is the one you need.
<?php
$a = "hello";
$b = "hell";
$str = "";
for ($i=0; $i < strlen($a); $i++) {
for ($j=0; $j < strlen($b); $j++) {
if ($a[$i]==$b[$j]) {
$str.=$a[$i];
break;
}
}
}
echo $str;
?>
PHP Strings can be seen as Char arrays so $a[0] get you the first char of the string.

PHP Scrape; save as variables for MySQL Insert

I'm successfully scraping a website to get space separated data off of the page:
$html = file_get_contents("http://www.somewebsite.com");
$scores_doc = new DOMDocument();
$scores_doc->loadHTML($html);
$scores_path = new DOMXPath($scores_doc);
$scores_row = $scores_xpath->query('//td[#class="first"]');
foreach($scores_row as $row){
echo $row->nodeValue . "<br/>";
}
Example output:
23 Crimmons, Bob (CA)
48 Silas, Greg (RI)
82 Huston, Roger (TX)
21 Lester, Terry (NC)
Instead of printing the output using 'echo' I need to split the value into four smaller pieces and into variables (array or otherwise). I know the MySQL side very well, I just don't use PHP day to day. I tried (in place of the 'echo' and after defining it as an array):
$data[] = echo $row->nodeValue;
A sidenote on the used syntax:
If you just want to assign the whole 23 Crimmons, Bob (CA) string as one string to an array. You should use the right syntax.
$data[] = echo $row->nodeValue;
Should be:
$data[] = $row->nodeValue;
Three possible solutions to your problem.
Solution 1: Improve scraping
The best way to scrape those four values seperately would be to query more specifically. You can try to update your xpath query on line:
$scores_xpath->query('//td[#class="first"]');
The query you can use depends on the structure of the page you're scraping.
Solution 2: Splitting string using PHP explode
You could use PHP's explode function to separate the string, but note that will give some problems when there are spaces used in a name.
echo $row->nodeValue . "<br/>";
Can be something like:
// Assuming that $row->nodeValue will have the string `23 Crimmons, Bob (CA)` as it's value
$explodeRow = explode(' ', $row->nodeValue);
/*
* $explodeRow now contains four values.
*
* $explodeRow[0] = "23";
* $explodeRow[1] = "Crimmons,";
* $explodeRow[2] = "Bob";
* $explodeRow[3] = "(CA)";
*/
You can choose to remove the ( and ) characters in $explodeRow[3] with the PHP str_replace, preg_replace or substr function for example.
Solution 3: Splitting string using regular expressions
Alternatively you can decide to fetch the first two numbers first. Then to fetch the last part between (). Then seperate the two remaining values by ,. But this can also generates problems when multiple commas are used.
Example of this solution will be, something like:
preg_match("~^(\d+)~", $row->nodeValue, $number);
$number[1]; # will be 23
preg_match("#\((.*?)\)#", $row->nodeValue, $last);
$last[1]; # will be CA
$middleExp = explode("(", $row->nodeValue, 2);
$middle = substr((strlen($number[1])-1), strlen($row->nodeValue), $middleExp[0]);
$middleExp2 = explode(",", $middle);
$middleL = $middleExp2[0]; # will be Crimmons
$middleR = $middleExp2[1]; # will be Bob

how to count hindi string in array with php and count how many letter and vowel in string

I have something like
$a = "आलोक"
I want to achieve something like in php
a[0] = आ
a[1] = लो
a[3] = क
I want counting in numbers like :-
i put a name आलोक
i want output like letter=3 and vowel=2
because in आलोक
first letter (आ),
second letter (लो)
and third letter is (क).
so out put become is letter= 3
and for vowel ,
first vowel ( ा) and
second vowel( ो)
so out put vowel=2
name can be dynamic not static
I was going through the other question you had posted and the accepted answer suggests a function on the following lines to break up the string into characters:
function mbStringToArray ($string) {
$strlen = mb_strlen($string);
while ($strlen) {
$array[] = mb_substr($string,0,1,"UTF-8");
$string = mb_substr($string,1,$strlen,"UTF-8");
$strlen = mb_strlen($string);
}
return $array;
}
$a = "आलोक";
print_r(mbStringToArray($a));
If you run this code, it will give you the following output:
Array
(
[0] => आ
[1] => ल
[2] => ो
[3] => क
)
I'm going to build upon this function and just extend it a little bit and you'll be able to get the count of vowels and consonants easily.
Thankfully, I found this handy guide on the UTF-8 encodings of all the characters in the Devnagri script. Another simple tool to confirm and sort of get the decimal and octal representations as well for this characters is http://unicodelookup.com/.
From the table, I looked up 0x093F and easily cross referenced it with ि.
Now once you have this, it's just a matter of getting the decoded unicode character from the HEX code. You can achieve that easily with :
echo json_decode('"\u093F"'); //Ouputs ि
I have combined these steps together in a function called countVowels:
function countVowels ($req){
//I have hard coded the hex values of some characters that are vowels in Hindi
//This does NOT include all the vowels
//You might want to add more as per your needs from the table that I have provided before
$hindi = array("\u0906","\u0908","\u093E","\u093F","\u0945","\u0946","\u0947","\u0948","\u0949","\u094A","\u094B","\u094C","\u094D");
$vowels= array();
$vowelcount = 0;
for($i = 0; $i<count($hindi); $i++){
//Push the decoded unicode character into the $vowels array
array_push($vowels,json_decode('"'.$hindi[$i].'"'));
}
for($j=0;$j<count($req);$j++){
if(in_array($req[$j], $vowels))
$vowelcount++;
}
return $vowelcount;
}
The input to this function is $req which could be the output array for the previously defined function mbStringToArray. Once you have the count of vowels, you can easily get the count of other consonants. The flow might look something like:
$a = "आलोक";
$arr = mbStringToArray($a)
$vows = countVowels($arr); //Number of vowels
$cons = count($arr) - $vows; //Number of consonants
So in this case, the consonants returned would be 2 and vowels would also be 2. That's because I have hardcoded आ as a vowel and therefore it gets accounted for in the countVowels function. Have a look at the working demo.
You can modify the array I use there and take care of such discrepancies as per your requirements. I hope this gets you started in the right direction.

Categories