I'm looking to get an array of ID's from the following string.
[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]
Ideally, i'd like to look at this string and get an array of the INT values within images. e.g.
array("3057", "2141", "234");
find images value and explode it to receive array
$str = '[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]';
if (preg_match('/images\s*=\s*\"([^\"]+)\"/', $str, $m)) {
$res = explode(',', $m[1]);
print_r($res);
}
Another solution using explode and strpos functions:
$str = '[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]';
foreach (explode(" ", $str) as $v) {
if (strpos($v, "images=") === 0) {
$result = explode(",", explode('"', $v)[1]);
break; // avoids redundant iterations
}
}
print_r($result);
The output:
Array
(
[0] => 3057
[1] => 2141
[2] => 234
)
Related
I have strings in following format:
$strings[1] = cat:others;id:4,9,13
$strings[2] = id:4,9,13;cat:electric-products
$strings[3] = id:4,9,13;cat:foods;
$strings[4] = cat:drinks,foods;
where cat means category and id is identity number of a product.
I want to split these strings and convert into arrays $cats = array('others'); and $ids = array('4','9','13');
I know that it can be done by foreach and explode function through multiple steps. I think I am somewhere near, but the following code does not work.
Also, I wonder if it can be done by preg_match or preg_split in fewer steps. Or any other simpler method.
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach($temps as $temp) {
$tempnest = explode(':', $temp);
$array[$tempnest[0]] .= explode(',', $tempnest[1]);
}
}
My desired result should be:
$cats = ['others', 'electric-products', 'foods', 'drinks';
and
$ids = ['4','9','13'];
One option could be doing a string compare for the first item after explode for cat and id to set the values to the right array.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
$cats = [];
$ids = [];
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = explode(',', $tempnest[1]);
}
if ($tempnest[0] === "id") {
$ids = explode(',', $tempnest[1]);
}
}
print_r($cats);
print_r($ids);
}
Php demo
Output for the first item would for example look like
Array
(
[0] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
If you want to aggregate all the values in 2 arrays, you can array_merge the results, and at the end get the unique values using array_unique.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
$cats = [];
$ids = [];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = array_merge(explode(',', $tempnest[1]), $cats);
}
if ($tempnest[0] === "id") {
$ids = array_merge(explode(',', $tempnest[1]), $ids);
}
}
}
print_r(array_unique($cats));
print_r(array_unique($ids));
Output
Array
(
[0] => drinks
[1] => foods
[3] => electric-products
[4] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
Php demo
I don't generally recommend using variable variables, but you are looking for a sleek snippet which uses regex to avoid multiple explode() calls.
Here is a script that will use no explode() calls and no nested foreach() loops.
You can see how the \G ("continue" metacharacter) allows continuous matches relative the "bucket" label (id or cat) by calling var_export($matches);.
If this were my own code, I'd probably not create separate variables, but a single array containing id and cat --- this would alleviate the need for variable variables.
By using the encountered value as the key for the element to be added to the bucket, you are assured to have no duplicate values in any bucket -- just call array_values() if you want to re-index the bucket elements.
Code: (Demo) (Regex101)
$count = preg_match_all(
'/(?:^|;)(id|cat):|\G(?!^),?([^,;]+)/',
implode(';', $strings),
$matches,
PREG_UNMATCHED_AS_NULL
);
$cat = [];
$id = [];
for ($i = 0; $i < $count; ++$i) {
if ($matches[1][$i] !== null) {
$arrayName = $matches[1][$i];
} else {
${$arrayName}[$matches[2][$i]] = $matches[2][$i];
}
}
var_export(array_values($id));
echo "\n---\n";
var_export(array_values($cat));
All that said, I probably wouldn't rely on regex because it isn't very readable to the novice regex developer. The required logic is much simpler and easier to maintain with nested loops and explosions. Here is my adjustment of your code.
Code: (Demo)
$result = ['id' => [], 'cat' => []];
foreach ($strings as $string) {
foreach (explode(';', $string) as $segment) {
[$key, $values] = explode(':', $segment, 2);
array_push($result[$key], ...explode(',', $values));
}
}
var_export(array_unique($result['id']));
echo "\n---\n";
var_export(array_unique($result['cat']));
P.s. your posted coding attempt was using a combined operator .= (assignment & concatenation) instead of the more appropriate combined operator += (assignment & array union).
this code is in php
$v = 1,2,3,4,5;
as I have to concat _1 in above variable
as I need this output $v = 1_1,2_1,3_1,4_1,5_1
Please refer to the PHP Manual:
implode — Join array elements with a string
explode — Split a string by string
In your case:
$v = "1,2,3,4,5";
echo implode("_1,", explode(",", $v)) . "_1";
On a side note: since your string is a comma separated value, you might also be interested in
str_getcsv — Parse a CSV string into an array
Without exploding/imploding, you can:
echo str_replace(',', '_1,', '1,2,3,4,5') . '_1';
$v = "1,2,3,4,5;";
$newValue = str_replace(",","_1,",$v); //replace , with _1,
$newValue = str_replace(";","_1;",$newValue); //replace ; with _1;
output:
1_1,2_1,3_1,4_1,5_1;
Use array map
$v = '1,2,3,4,5';
$arr = explode(',',$v);
$arr = array_map(function ($val){
return $val.'_1';
},$arr);
echo implode(',',$arr);
demo
I think you should put those numbers in quote.
$v = '1,2,3,4,5';
$new_v = explode(',', $v);
foreach ($new_v as $x) {
$v1[] = $x.'_1';
}
print_r($v1);
It will return array like this.
Array ( [0] => 1_1 [1] => 2_1 [2] => 3_1 [3] => 4_1 [4] => 5_1 )
Hi I got the following string:
info:infotext,
dimensions:dimensionstext
and i need to put these values into an array in PHP. What is the regex function to put these into an array. I studied the regex codes but it's kinds confusing to me.
I want to put the info as the key and he infotext as the value into an array like this:
Array {
[info] => infotext
[dimensions] => dimensionstext
}
Demo here
<?php
$string ='info:infotext,
dimensions:dimensionstext';
$array = array_map(function($v){return explode(':', trim($v));}, explode(',', $string));
foreach($array as $v)
{
$o[$v[0]] = $v[1];
}
print_r($o);
You can use array_chunk and array_combine
<?php
$input = 'info:infotext,
dimensions:dimensionstext';
$chunks = array_chunk(preg_split('/(:|,)/', $input), 2);
$result = array_combine(array_column($chunks, 0), array_column($chunks, 1));
print_r($result);
http://ideone.com/dRtref
Consider an array like this,
$sports = array('Football','cricket ball','tennis ball','shuttle bat','hockey stick');
I want to create an array from $sports like this,
$ball = array('Football','cricket ball','tennis ball');
based on the search key(here it is 'ball').
If am looping through the array $sports and checking one by one, will get the result. But then am already inside a loop and that may be even loops more than 50,000 times. So thought of avoiding another loop.
Is there any other way to get this done?
Thanks
Try array_filter() + preg_match() functions:
<?php
header('Content-Type: text/plain; charset=utf-8');
$array = array('Football','cricket ball','tennis ball','shuttle bat','hockey stick');
$word = 'ball';
$results = array_filter(
$array,
function($value) use ($word){
return preg_match('/' . $word . '/i', $value);
}
);
print_r($results);
?>
Shows:
Array
(
[0] => Football
[1] => cricket ball
[2] => tennis ball
)
$sports = array('Football','cricket ball','tennis ball','shuttle bat','hockey stick');
$input = 'ball';
$result = array_filter($sports, function ($item) use ($input) {
if (stripos($item, $input) !== false) {
return $item;
}
});
print_r($result);
This is my array output
Array
(
[0] => Array
(
[tweet_text] => Fedora 16 "Verne" released! http://t.co/lECbdzE0 #Fedora #Linux
)
[1] => Array
(
[tweet_text] => Ubuntu 11.10 "Oneiric Ocelot" released! #Ubuntu #Linux
)
)
Example to find Ubuntu keyword. From the current array how do I filter to show only
Array ( [1] => Array (
[tweet_text] => Ubuntu 11.10 "Oneiric Ocelot" released! #Ubuntu #Linux
)
)
The code
$keywords = array('Ubuntu');
foreach ($keywords as &$keyword) {
$keyword = preg_quote($keyword);
}
$regex = "/(" . implode('|', $keywords) . ")/";
$check = preg_match($regex, $anArray);
if($check == 1) {
// here I want to display only Ubuntu
}
Let me know
preg_grep — Return array entries that match the pattern
example:-
$arr = array('k'=>'ubuntu', 'j'=>'ubuntu1', 'n'=>'fedorra');
$matches = preg_grep('/ubuntu/i', $arr);
if you original source is an multi-dimensional array,
you can try :-
$cmp = array();
foreach ($src as $key=>$arr)
{
$cmp[$key] = $arr['tweet_text'];
}
$matches = preg_grep('/ubuntu/i', $cmp);
// $matches will be an associate array contains the matches
// and $matches and $src are using same index key
There are a few approaches here, basically you could look at your current function: preg_match. By the way i don't think you can put a array into the subject parameter if it requires a string. For now i will guess you are putting a string there with the wrong name.
You could use it also to save the matches found like so:
$check = preg_match($regex, $string, $matches);
print_r($matches);
If it is an array you should approach it like a single result and loop trough it (there are betters ways, but this is an approach you are using and i try to teach you this better.
// Your code ....
foreach($anArray as $rule) {
$check = preg_match($regex, $anArray, $matches);
if($check == 1) {
echo print_r($matches);
}
}