Preg_match_all counter? - php

<?
echo "Begin Function=";
echo "<br>";
$text = "2lyve: this is: 8475978474957845 948594: jfhdhfkd: just the 2lyve: beginning:";
function getTrends($text)
{
$subject = $text;
$pattern ='/(\w+:)/Ui';
preg_match_all($pattern, $subject, $matches);
foreach($matches[1] as $value)
{
print $value."<br>";
}
}
getTrends($text);
?>
The result will be:
Begin Function=
2lyve:
is:
948594:
jfhdhfkd:
2lyve:
beginning:
How do I count how many times each result is returned and rank it? Also, how to I import these results into a sql database?

PHP actually has a specific function for this purpose.
array_count_values
Your code could be changed to
<?php
echo "Begin Function=";
echo "<br>";
$text = "2lyve: this is: 8475978474957845 948594: jfhdhfkd: just the 2lyve: beginning:";
function getTrends($text)
{
$subject = $text;
$pattern ='/(\w+:)/Ui';
preg_match_all($pattern, $subject, $matches);
$findings = array_count_values($matches[1]);
foreach($findings as $value=>$occ)
{
print $value."<br>";
}
}
getTrends($text);
?>

Declare an array $map = array(); in the start of your function, and then in the place of
print $value."<br>";
put
if(isset($map[$value])) {
$map[$value]++;
} else {
$map[$value] = 1;
}

Related

How can I hide a string if it doesn't contain one of multiple words?

I already have a code:
<?
$eventname = $event->title;
$bad_words = array('Example1','Example2','Example3','Example4','Example5','Example6');
foreach($bad_words as $bad_word){
if(strpos($eventname, $bad_word) !== false) {
echo '';
break;
}
else {
echo '<div class="uk-text-contrast">'.translate('HIDDEN_INFO_DATE').'</div>';
break;
}
}
?>
this works, but only if the $eventname contains example1. But I want to hide echo '<div class="uk-text-contrast">'.translate('HIDDEN_INFO_DATE').'</div>'; from all of the defined words in the $bad_words.
How can I hide the echo if there is one of the $bad_words?
Why don't you use the in_array function? It's even shorter in that way.
if (in_array($eventname, $bad_words)) {
echo '';
} else {
echo '<div>';
}
remobe 'break' from code
foreach($bad_words as $bad_word){
if(strpos($eventname, $bad_word) !== false) {
echo '';
}
else {
echo '<div class="uk-text-contrast">'.translate('HIDDEN_INFO_DATE').'</div>';
}
}
I would convert the string $eventname to an array and then use the array Intersect function
$eventname = "sgswfdg Example1 sdfh dh dfa hadhadh";
$title_to_array=explode(" ", $eventname);
$bad_words = array('Example1','Example2','Example3','Example4','Example5','Example6');
$result = !empty(array_intersect($bad_words , $title_to_array ));
if ($result){
echo '';
} else {
echo $eventname;
}
Rather than using a loop, you could split the title into it's separate words and then check if there are any words in the $bad_words list using array_intersect()
// $eventname = $event->title;
$eventname = 'Some text';
$eventname = 'Some text Example1';
$bad_words = array('Example1','Example2','Example3','Example4','Example5','Example6');
$eventWords = explode(" ", $eventname);
if ( empty (array_intersect($eventWords, $bad_words))) {
// Event name is OK
echo $eventname;
}
This has some examples to show how it works.
Note that this code doesn't pick up things like Example1234 which strpos() would.
Update:
Just to make it more flexible, you can use regular expressions in case you have punctuation in the title...
$eventname = 'Some text';
$eventname = 'Some text,Example1';
$bad_words = array('Example1','Example2','Example3','Example4','Example5','Example6');
preg_match_all('/(\w+)/', $eventname, $eventWords);
if ( empty (array_intersect($eventWords[1], $bad_words))) {
echo '<div class="uk-text-contrast">'.translate('HIDDEN_INFO_DATE').'</div>';
}
( Note: Regular expressions aren't my subject so please let me know if this needs to be improved).

Multiple preg_match_all result in foreach

I would like to replace each decimal number for later using in Javascript. so This is my code:
if (preg_match_all("#[0-9]+(\.[0-9]{1,8})#", $operationvalue_new2, $result)) {
foreach ($result[0] as $number_element) {
$operationvalue_new2 = preg_replace(
"#[0-9]+(\.[0-9]{1,8})#",
"Number(\\0)",
$operationvalue_new2
);
#echo $operationvalue_new2;
}
};
Here is an example what happens:
//var1812/100*(var1805*var1807*2.688)+(var1808-var1812)*var1806*var1807*1.2/100)
will be converted to
//var1812/100*(var1805*var1807*Number(Number(2.688)))+(var1808-var1812)*var1806*var1807*Number(Number(1.2))/100)
but should be
//var1818=var1812/100*(var1805*var1807*Number(2.688))+(var1808-var1812)*var1806*var1807*Number(1.2)/100)
Try this:
<?php
$subject = "var1812/100*(var1805*var1807*2.688)+(var1808-var1812)*var1806*var1807*1.2/100)";
$result = preg_replace('/([0-9]+\.[0-9]{1,8})/s', 'number($1)', $subject);
echo $result;
?>
Results in:
var1812/100*(var1805*var1807*number(2.688))+(var1808-var1812)*var1806*var1807*number(1.2)/100)

What is the simplest way to split this string using PHP?

I have the below string in PHP.
:guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP
I need to create these variables from the string:
$nick = guest
$user = lbjpewueqi
$host = AF8A326D.E0B4A40D.F85DC93A.IP
What is the best function to use to do this?
Ideally I would like to create some sort of function so I can pass to it the string and what part I want returned.
For example:
$string = "guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
echo stringToPart($string, nick);
guest
echo stringToPart($string, nick);
lbjpewueqi
echo stringToPart($string, host);
AF8A326D.E0B4A40D.F85DC93A.IP
Another version:
function stringToPart($string, $part) {
if (preg_match('/^:(.*)!(.*)#(.*)/', $string, $matches)) {
$nick = $matches[1];
$user = $matches[2];
$host = $matches[3];
return isset($$part) ? $$part : null;
}
}
More strict than preg_split solutions - it checks separators order.
Maybe this code may helpful for you
$p = '/[:!#]/';
$s = ":guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
print_r( preg_split( $p, $s ), 1 );
You can declare a function like this:
$s = ":guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
function stringToPart($str, $part) {
$pat['nick'] = '/:(.*)!/';
$pat['user'] = '/.*!(.*)#/';
$pat['host'] = '/#(.*)/';
preg_match($pat[$part], $str, $m);
if (count($m) > 1) return $m[1];
return null;
}
echo stringToPart($s,'nick')."\n";
echo stringToPart($s,'user')."\n";
echo stringToPart($s,'host')."\n";
The below should do what you're looking for.
$pattern = "/[:!#]/";
$subject = ":guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
print_r(preg_split($pattern, $subject));
The pattern is specifying what characters to split on so you could in theory have any amount of characters here if there were other instance you needed to account for different strings being passed in.
To return the values instead of just printing then to the screen use this:
$pattern = "/[:!#]/";
$subject = ":guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
$result = preg_split($pattern, $subject));
$nick = $result[1];
$user = $result[2];
$host = $result[3];
stringToPart(':guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP','nick');
function stringToPart($string, $type){
$result['nick']= substr($string,strpos($string,':')+1,(strpos($string,'!')-strpos($string,':')-1));
$result['user']= substr($string,strpos($string,'!')+1,(strpos($string,'#')-strpos($string,'!')-1));
$result['host']= substr($string,strpos($string,'#')+1);
return $result[$type];
}
<?php
function stringToPart($string, $key)
{
$matches = null;
$returnValue = preg_match('/:(?P<nick>[^!]*)!(?P<user>.*?)#(?P<host>.*)/', $string, $matches);
if (isset($matches[$key]))
{
return $matches[$key];
} else
{
return NULL;
}
}
$string = ':guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP';
echo stringToPart($string, "nick");
echo "<br />";
echo stringToPart($string, "user");
echo "<br />";
echo stringToPart($string, "host");
echo "<br />";
?>

Repeat a php code - how to?

I want this code to repeat for the given id ( if it doesn't find for id shown in example so it will go for 1232 (+1) and so on untill it finds a good id that has the preg_matsh "flv_url" and stops showing me the id that worked)
<?php
$id=1231;
$text = file_get_contents("http://www.exemple.com/video". $id ."");
if (preg_match('~flv_url=(.*?)&~si', $text, $body)){
$decoded_url = rawurldecode($body[1]);
echo $decoded_url;
}
else {}
?>
<?php
$id=1231;
$match = false;
do {
$text = file_get_contents("http://www.exemple.com/video". $id++ ."");
if (preg_match('~flv_url=(.*?)&~si', $text, $body)){
$match = true;
$decoded_url = rawurldecode($body[1]);
echo $decoded_url;
}
} while(!$match);
?>
you need to use while() or for() or do() for repeat your code.code will repeat according to your conditions
You can use for();
<?php
for($id=1231;$id!=-1;$id++){
$text = file_get_contents("http://www.exemple.com/video". $id ."");
if (preg_match('~flv_url=(.*?)&~si', $text, $body)){
$decoded_url = rawurldecode($body[1]);
echo $decoded_url;
$id = -1;
}
else {}
}
?>

preg_replace successful or not

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
}

Categories