I need to split this kind of strings to separate the email between less and greater than < >. Im trying with the next regex and preg_split, but I does not works.
"email1#domain.com" <email1#domain.com>
News <news#e.domain.com>
Some Stuff <email-noreply#somestuff.com>
The expected result will be:
Array
(
[0] => "email1#domain.com"
[1] => email#email.com
)
Array
(
[0] => News
[1] => news#e.domain.com
)
Array
(
[0] => Some Stuff
[1] => email-noreply#somestuff.com
)
Code that I am using now:
foreach ($emails as $email)
{
$pattern = '/<(.*?)>/';
$result = preg_split($pattern, $email);
print_r($result);
}
You may use some of the flags available for preg_split: PREG_SPLIT_DELIM_CAPTURE and PREG_SPLIT_NO_EMPTY.
$emails = array('"email1#domain.com" <email1#domain.com>', 'News <news#e.domain.com>', 'Some Stuff <email-noreply#somestuff.com>');
foreach ($emails as $email)
{
$pattern = '/<(.*?)>/';
$result = preg_split($pattern, $email, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($result);
}
This outputs what you expect:
Array
(
[0] => "email1#domain.com"
[1] => email1#domain.com
)
Array
(
[0] => News
[1] => news#e.domain.com
)
Array
(
[0] => Some Stuff
[1] => email-noreply#somestuff.com
)
Splitting on something removes the delimiter (i.e. everything the regex matches). You probably want to split on
\s*<|>
instead. Or you can use preg_match with the regex
^(.*?)\s*<([^>]+)>
and use the first and second capturing groups.
This will do the job. click here for Codepad link
$header = '"email1#domain.com" <email1#domain.com>
News <news#e.domain.com>
Some Stuff <email-noreply#somestuff.com>';
$result = array();
preg_match_all('!(.*?)\s+<\s*(.*?)\s*>!', $header, $result);
$formatted = array();
for ($i=0; $i<count($result[0]); $i++) {
$formatted[] = array(
'name' => $result[1][$i],
'email' => $result[2][$i],
);
}
print_r($formatted);
preg_match_all("/<(.*?)>/", $string, $result_array);
print_r($result_array);
$email='"email1#domain.com" <email1#domain.com>
News <news#e.domain.com>
Some Stuff <email-noreply#somestuff.com>';
$pattern = '![^\>\<]+!';
preg_match_all($pattern, $email,$match);
print_r($match);
Ouput:
Array ( [0] => Array (
[0] => "email1#domain.com"
[1] => email1#domain.com
[2] => News
[3] => news#e.domain.com
[4] => Some Stuff
[5] => email-noreply#somestuff.com ) )
You can also split by <, and get rid of ">" in $result
$pattern = '/</';
$result = preg_split($pattern, $email);
$result = preg_replace("/>/", "", $result);
Related
I'm a bit lost with preg_split() in parsing a string with multiple delimiters and keeping the delimiter in the 'after' part of the split.
My delimiters are $, #, and ?.
For instance:
$str = 'participant-$id#-group';
$ar = preg_split('/([^$#?]+[$#?]+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
echo "<pre>"; print_r( $ar); echo "</pre>";
will show:
Array
(
[0] => participant_data-$
[1] => id#
[2] => -group
)
However I need:
Array
(
[0] => participant_data-
[1] => $id
[2] => #-group
)
Regex makes my brain hurt. so could someone advise how I use PREG_SPLIT_DELIM_CAPTURE and keep the delimiter at the beginning of the segment?
Try this:
$ar = preg_split('/(\$[^#]+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
How about this. I am capturing the delimiters and then put them back together.
<?php
$str = 'participant-$id#-group';
$ar = preg_split('/([^$#?]+[^$#?]+)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
echo "<pre>"; print_r( $ar); echo "</pre>";
/*
Array
(
[0] => participant-
[1] => $
[2] => id
[3] => #
[4] => -group
) */
$result = array();
$result[] = $ar[0];
for($i=1;$i<count($ar);$i+=2) {
$result[] = $ar[$i] . $ar[$i+1];
}
echo "<pre>"; print_r( $result); echo "</pre>";
/*
Array
(
[0] => participant-
[1] => $id
[2] => #-group
)
*/
?>
You don't need to capture the delimiters, just use a lookahead for the $, #, or ?. This will split your string on the zero-width position before the delimiters. No characters will be lost/consumed why exploding.
Code: (Demo)
$str = 'participant-$id#-group';
var_export(
preg_split('/(?=[$#?])/', $str)
);
Output:
array (
0 => 'participant-',
1 => '$id',
2 => '#-group',
)
Hi I have been doing this project for almost a month now. Is there's anyway I can store the value of the next string after the searched string in the list of array?
For example:
Deviceid.txt content is:
Created:21/07/2016 1:50:53; Lat:30.037853; Lng:31.113798; Altitude:79; Speed:0; Course:338; Type:Gps;
Created:21/07/2016 1:49:53; Lat:30.037863; Lng:31.113733; Altitude:60; Speed:0; Course:338; Type:Gps;
Here is my sample php coding
$file_handle = fopen("data/deviceid.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
array_push($a,$line);
}
$searchword = 'Lat';
$matches = array_filter($a, function($var) use ($searchword) {
return preg_match("/\b$searchword\b/i", $var);
});
print_r($matches);
fclose($file_handle);
Matches Data:
[0] = 30.037853
[1] = 30.037863
After parsing the file with the code below, you can use array_column (php v5.5.0+) to get all values from a specific key, like so:
array_column($parsed, 'Lat');
Output:
Array
(
[0] => 30.037853
[1] => 30.037863
)
See it in action here.
And here is the code to parse the content of the file:
// $a = each line of the file, just like you're doing
$a = array_filter($a); // remove empty lines
$parsed = array();
foreach($a as $v1){
$a1 = explode(';', $v1);
$tmp = array();
foreach($a1 as $v2){
$t2 = explode(':', $v2);
if(count($t2) > 1){
$tmp[trim(array_shift($t2))] = trim( implode(':', $t2) );
}
}
$parsed[] = $tmp;
}
This is the structure of $parsed:
Array
(
[0] => Array
(
[Created] => 21/07/2016 1:50:53
[Lat] => 30.037853
[Lng] => 31.113798
[Altitude] => 79
[Speed] => 0
[Course] => 338
[Type] => Gps
)
[1] => Array
(
[Created] => 21/07/2016 1:49:53
[Lat] => 30.037863
[Lng] => 31.113733
[Altitude] => 60
[Speed] => 0
[Course] => 338
[Type] => Gps
)
)
See the code in action here.
I wrote a quick regex that can help you pull the field names and values from each line.
You may try with this:
$re = "/((?P<fieldname>[^\\:]*)\\:(?P<fieldvalue>[^\\;]*); *)/";
$str = "Created:21/07/2016 1:50:53; Lat:30.037853; Lng:31.113798; Altitude:79; Speed:0; Course:338; Type:Gps;";
preg_match_all($re, $str, $matches);
Do a print_r of $matches to inspect the results.
Hope this helps.
After your array_filter, iterate through your matches and apply a more specific regex to each line:
$lats = array();
foreach ($matches as $line)
{
$match = array();
preg_match("/\b$searchword:([\d\.]+);/i", $var, $match);
$lats[] = $match[1];
}
print_r($lats);
The variable $match will be populated with the full regex match at index 0, and the parenthesized match at index 1.
I have a string that has hash tags in it and I'm trying to pull the tags out I think i'm pretty close but getting a multi-dimensional array with the same results
$string = "this is #a string with #some sweet #hash tags";
preg_match_all('/(?!\b)(#\w+\b)/',$string,$matches);
print_r($matches);
which yields
Array (
[0] => Array (
[0] => "#a"
[1] => "#some"
[2] => "#hash"
)
[1] => Array (
[0] => "#a"
[1] => "#some"
[2] => "#hash"
)
)
I just want one array with each word beginning with a hash tag.
this can be done by the /(?<!\w)#\w+/ regx it will work
That's what preg_match_all does. You always get a multidimensional array. [0] is the complete match and [1] the first capture groups result list.
Just access $matches[1] for the desired strings. (Your dump with the depicted extraneous Array ( [0] => Array ( [0] was incorrect. You get one subarray level.)
I think this function will help you:
echo get_hashtags($string);
function get_hashtags($string, $str = 1) {
preg_match_all('/#(\w+)/',$string,$matches);
$i = 0;
if ($str) {
foreach ($matches[1] as $match) {
$count = count($matches[1]);
$keywords .= "$match";
$i++;
if ($count > $i) $keywords .= ", ";
}
} else {
foreach ($matches[1] as $match) {
$keyword[] = $match;
}
$keywords = $keyword;
}
return $keywords;
}
Try:
$string = "this is #a string with #some sweet #hash tags";
preg_match_all('/(?<!\w)#\S+/', $string, $matches);
print_r($matches[0]);
echo("<br><br>");
// Output: Array ( [0] => #a [1] => #some [2] => #hash )
I have a text file countries.txt with a list of all countries:
1. Australia
2. Austria
3. Belgium
4. US
I want to create an array in country_handler.php like this:
$countries = array(
'1'=>'Australia',
'2'=>'Austria',
'3'=>'Belgium',
'4'=>'US'
);
How to do that?
Better you can use this in a function like below - then just called this function from any where
function getCountryList()
{
return array(
'1'=>'Australia',
'2'=>'Austria',
'3'=>'Belgium',
'4'=>'US'
);
}
$data = file_get_contents('countries.txt');
$countries = explode(PHP_EOL, $data);
$file = file('countries.txt');
$countries = array();
foreach ($file as $line) {
#list ($index, $country) = explode('.', $line);
$countries[trim($index)] = trim($country);
}
print_r($countries);
$lines = file('countries.txt');
$newArr = array();
foreach ($lines as $line) {
$erg = preg_split('/\.\s+/', $line);
$newArr[$erg[0]] = $erg[1];
}
var_dump($newArr);
Luckily (sometimes) regex doesn't include newlines in the ., so you can do this:
$contents = file_get_contents('countries.txt');
preg_match_all('#(\d+)\.\s+(.+)#', $contents, $matches);
print_r($matches);
The regex means:
(\d+) -- a number (save this)
\. -- a literal dot
\s+ -- white space
(.+) -- any character except \n or \r (end-of-line) (save this)
Which results in:
Array
(
[0] => Array
(
[0] => 1. Australia
[1] => 2. Austria
[2] => 3. Belgium
[3] => 4. US
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[2] => Array
(
[0] => Australia
[1] => Austria
[2] => Belgium
[3] => US
)
)
and I'm sure from [1] and [2] you can make the keyed array you need.
array_combine to the easy rescue:
$countries = array_combine($matches[1], $matches[2]);
Try this:
<?php
$data = file_get_contents('countries.txt');
$countries = explode(PHP_EOL,$data);
$cnt = 1;
foreach($countries as $val) {
if($val <>"") {
$res[$cnt] = strstr(trim($val), ' ');
$cnt++;
}
}
print_r($res);
?>
So I'm trying to get all the urls from a string with a script that looks like this:
$file = file_get_contents('something.txt');
function getUrls($string) {
preg_match_all('~href=("|\')(.*?)\1~', $string, $out);
print_r($out);
}
getUrls($file);
The urls contained in this document may be imperfect - i.e. "/blah/blah.asp?2". The problem is that when I run this script, I get an array that looks something like this:
Array
(
[0] => Array
(
[0] => href="#A"
[1] => href="#B"
[2] => href="#C"
)
[1] => Array
(
[0] => "
[1] => "
[2] => "
)
[2] => Array
(
[0] => #A
[1] => #B
[2] => #C
)
)
Any idea what could be going on here? I have no idea why it is returning alphabetical lists with hash signs instead of the desired urls. How can I go about just returning the urls?
The way of evil:
$file = file_get_contents('something.txt');
function displayUrls($string) {
$pattern = '~\bhref\s*+=\s*+["\']?+\K(?!#)[^\s"\'>]++~';
preg_match_all($pattern, $string, $out);
print_r($out[0]);
}
displayUrls($file);
The good way:
$doc = new DOMDocument();
#$doc->loadHTMLFile('something.txt');
$links = $doc->getElementsByTagName('a');
foreach($links as $link) {
$href = $link->getAttribute('href');
if ($href[0] != '#') $result[] = $href;
}
print_r($result);