this is my code that extracts the date "2016-06-13" from the string "ffg_LTE_2016-06-13"
$re = '/(\d{8})|([0-9]{4}-[0-9]{2}-[0-9]{2})|([0-9]{2}-[0-9]{2}-[0-9]{4})/';
$str = "ffg_LTE_2016-06-13";
preg_match($re, $str, $matches);
$date=$matches[0];
print_r($date);
Now what I want to do is do somthing like this in a for loop but I am having issues with storing the result in an array. What I want to do is the same as above but do it on each elememt in the array.
$files=["ffg_LTE_2016-06-13","ffg_LTE_2016-06-14"];
foreach ($files as $value) {
print_r("<br>".$value."<br>");
}
So my end result would be
$files_2=["2016-06-13","2016-06-14"];
here is my fiddle
You can try this:
<?php
$files=["ffg_LTE_2016-06-13","ffg_LTE_2016-06-14"];
$re = '/(\d{8})|([0-9]{4}-[0-9]{2}-[0-9]{2})|([0-9]{2}-[0-9]{2}-[0-9]{4})/';
$results = [];
foreach ($files as $value) {
preg_match($re, $value, $matches);
$results[] = $matches[0];
}
print_r($results);
?>
It just loops through $files, pushes the first match into the array $results, and prints out $results.
Related
I have a string
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
Need to convert this string in below format.
$utmcsr = google;
$utmcmd= organic;
$utmccn= (not set);
$utmctr= (not provided);
and more can come. I have try explode and slip function but not gives result. Please suggest.
Thanks in advance
With "Double explode" you can extract all key-value pairs from the string. First, explode on the pipe symbol, the resuting array contains strings like utmcsr=google. Iterate over this array and explode each string on the equal sign:
$result = [];
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
$arr = explode('|', $str);
foreach($arr as $str2) {
$values = explode('=', $str2);
$result[ $values[0] ] = $values[1];
}
Try this one
$str = 'utmcsr=google|utmcmd=organic|utmccn=(not set)|utmctr=(not provided)';
$new_array = explode('|', $str);
$result_array = array();
foreach ($new_array as $value) {
$new_arr = explode('=', $value);
$result_array[$new_arr[0]] = $new_arr[1];
}
extract($result_array);
echo $utmcsr;
echo $utmctr;
Output: google(not provided)
I have string like this
$string = 'title,id,user(name,email)';
and I want result to be like this
Array
(
[0] => title
[1] => id
[user] => Array
(
[0] => name
[1] => email
)
)
so far I tried with explode function and multiple for loop the code getting ugly and i think there must be better solution by using regular expression like preg_split.
Replace the comma with ### of nested dataset then explode by a comma. Then make an iteration on the array to split nested dataset to an array. Example:
$string = 'user(name,email),office(title),title,id';
$string = preg_replace_callback("|\(([a-z,]+)\)|i", function($s) {
return str_replace(",", "###", $s[0]);
}, $string);
$data = explode(',', $string);
$data = array_reduce($data, function($old, $new) {
preg_match('/(.+)\((.+)\)/', $new, $m);
if(isset($m[1], $m[2]))
{
return $old + [$m[1] => explode('###', $m[2])];
}
return array_merge($old , [$new]);
}, []);
print '<pre>';
print_r($data);
First thanks #janie for enlighten me, I've busied for while and since yesterday I've learnt a bit regular expression and try to modify #janie answer to suite with my need, here are my code.
$string = 'user(name,email),title,id,office(title),user(name,email),title';
$commaBetweenParentheses = "|,(?=[^\(]*\))|";
$string = preg_replace($commaBetweenParentheses, '###', $string);
$array = explode(',', $string);
$stringFollowedByParentheses = '|(.+)\((.+)\)|';
$final = array();
foreach ($array as $value) {
preg_match($stringFollowedByParentheses, $value, $result);
if(!empty($result))
{
$final[$result[1]] = explode('###', $result[2]);
}
if(empty($result) && !in_array($value, $final)){
$final[] = $value;
}
}
echo "<pre>";
print_r($final);
I am using regex to match pattern. Then pushing matched result using pushToResultSet. In both way of doing, would $resultSet have similar array content? Similar means not
insense of value, but format. I want to use 2nd way in alternative to 1st code.
UPDATE: Example with sample input http://ideone.com/lIaP49
foreach ($words as $word){
$pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE );
$this->pushToResultSet($matches);
}
return $resultSet;
Now I am doing this in another way and pushing array in similar way. As $matches is array and here $b is also array, I guess both code are similar
$b = array();
$pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
foreach ($test as $value)
{
$value = strtolower($value);
// Capture also the numbers so we just concat later, no more string substitution.
$matches = preg_split('/(\d+)/', $value, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
if ($matches)
{
$newValue = array();
foreach ($matches as $word)
{
// Replace if a valid word number.
$newValue[] = (isset($arrwords[$word]) ? $arrwords[$word] : $word);
}
$newValue = implode($newValue);
if (preg_match($pattern, $newValue))
{
$b[] = $value;
$this->pushToResultSet($b);
}
}
}
//print_r($b);
return $resultSet;
UPDATE
ACtual code which I want to replace out with 2nd code in the question:
<?php
class Phone extends Filter{
function parse($text, $words)
{
$arrwords = array(0=>'zero',1=>'one',2=>'two',3=>'three',4=>'four',5=>'five',6=>'six',7=>'seven',8=>'eight',9=>'nine');
preg_match_all('/[A-za-z]+/', $text, $matches);
$arr=$matches[0];
foreach($arr as $v)
{
$v = strtolower($v);
if(in_array($v,$arrwords))
{
$text= str_replace($v,array_search($v,$arrwords),$text);
}
}
//$resultSet = array();
$l = strlen($text);
foreach ($words as $word){
$pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE );
//print_r($matches);
}
//print_r($matches);
$this->pushToResultSet($matches);
return $resultSet;
}
}
After running both codes, run PHP's var_dump function on the output variables.
If the printed output matches for your definition of similar array content, then your answer is yes. Otherwise, your answer is no.
I have following set of an array
array('www.example.com/','www.example.com','www.demo.example.com/','www.example.com/blog','www.demo.com');
and I would like to get all element which matching following patterns,
$matchArray = array('*.example.com/*','www.demo.com');
Expected result as
array('www.example.com/','www.demo.example.com/','www.example.com/blog','www.demo.com');
Thanks :)
This works:
$valuesArray = array('www.example.com/','www.example.com','www.demo.example.com/','www.example.com/blog','www.demo.com');
$matchArray = array('*.example.com/*','www.demo.com');
$matchesArray = array();
foreach ($valuesArray as $value) {
foreach ($matchArray as $match) {
//These fix the pseudo regex match array values
$match = preg_quote($match);
$match = str_replace('\*', '.*', $match);
$match = str_replace('/', '\/', $match);
//Match and add to $matchesArray if not already found
if (preg_match('/'.$match.'/', $value)) {
if (!in_array($value, $matchesArray)) {
$matchesArray[] = $value;
}
}
}
}
print_r($matchesArray);
But I would reccomend changing the syntax of your matches array to be actual regex patterns so that the fix section of code is not required.
/\w+(\.demo)?\.example\.com\/\w*|www\.demo\.com/
regexr link
I've got an array called $myarray with values like these:
myarray = array (
[0] => eat-breakfast
[1] => have-a-break
[2] => dance-tonight
[3] => sing-a-song
)
My goal is to search for a part of this array and get the rest of it. Here is an example:
If i submit eat, I would like to get breakfast.
If i submit have, I would like to get a-break.
I just try but I'm not sure at all how to do it...
$word = 'eat';
$pattern = '/'.$word.'/i';
foreach ($myarray as $key => $value) {
if(preg_match($pattern, $value, $matches)){
echo $value;
}
}
print_r($matches);
It displays:
eat-breakfastArray ( )
But I want something like that:
breakfast
I think I'm totally wrong, but I don't have any idea how to proceed.
Thanks.
use
stripos($word, $myarray)
<?php
$myarray = array (
'eat-breakfast',
'have-a-break',
'dance-tonight',
'sing-a-song'
) ;
function search($myarray, $word){
foreach($myarray as $index => $value){
if (stripos($value, $word) !== false){
echo str_replace(array($word,'-'), "", $value);
}
}
}
search($myarray, 'dance');
echo "<br />";
search($myarray, 'have-a');
echo "<br />";
search($myarray, 'sing-a');
demo
I think the word you seek is at the beginning. Try this
function f($myarray, $word)
{
$len = strlen($word);
foreach($myarray as $item)
{
if(substr($item, 0, $len) == $word)
return substr($item, $len+1);
}
return false;
}
You're feeding the wrong information into preg_match, although I'd recommend using array_search().. Check out my updated snippet:
$word = 'eat';
$pattern = '/'.$word.'/i';
foreach ($myarray as $key => $value) {
if(preg_match($pattern, $value, $matches)){
echo $value;
}
}
print_r($matches);
To get rid of that last bit, just perform a str_replace operation to replace the word with ""
This will both search the array (with a native function) and return the remainder of the string.
function returnOther($search, $array) {
$found_key = array_search($search, $array);
$new_string = str_replace($search . "-", "", $array[$found_key]);
return $new_string;
}