I want to get file name (with extension .png or .jpg or .gif) from the string given below :
{src:"brand.png", id:"brand"},
{src:"centpourcent.png", id:"centpourcent"},
{src:"corsa.png", id:"corsa"},
{src:"cta.png", id:"cta"},
{src:"neons.png", id:"neons"}
From the above string i want to get output like :
[ brand.png, centpourcent.png, corsa.png, cta.png, neons.png ] // Or may be as string output
I tried below code but it didnt work for me:
substr($images, strpos($images, "src:") + 5);
Im getting output as
brand.png", id:"brand"},
{src:"centpourcent.png", id:"centpourcent"},
{src:"corsa.png", id:"corsa"},
{src:"cta.png", id:"cta"},
{src:"neons.png", id:"neons"}
<?php
$string = '{src:"brand.png", id:"brand"},
{src:"centpourcent.png", id:"centpourcent"},
{src:"corsa.png", id:"corsa"},
{src:"cta.png", id:"cta"},
{src:"neons.png", id:"neons"}';
// Here I replace the src with "src" and id with "id"
$string = str_replace(['src', 'id'], ['"src"', '"id"'], $string);
// Then I wrap all the string in brackets to convert the string to valid JSON string.
$json = '[' . $string . ']';
// Finally I decode the JSON string into a PHP array.
$data = json_decode($json);
// Here I am going to save the images names.
$images = [];
// Here I itterate the json body entries and I push into the $images array
// the image name
foreach($data as $entry) {
array_push($images, $entry->src);
}
// And here I just print it out, to make sure the output is the following:
print_r($images);
// OUTPUT:
// Array
// (
// [0] => brand.png
// [1] => centpourcent.png
// [2] => corsa.png
// [3] => cta.png
// [4] => neons.png
// )
You can preg_match_all() use to get all file names.
$str = '{src:"brand.png", id:"brand"},
{src:"centpourcent.png", id:"centpourcent"},
{src:"corsa.png", id:"corsa"},
{src:"cta.png", id:"cta"},
{src:"neons.png", id:"neons"}';
$r = preg_match_all('~(?:src:")([^"]+)(?:")~',$str,$match);
var_dump($match[1])
Output:
array(5) {
[0]=>
string(9) "brand.png"
[1]=>
string(16) "centpourcent.png"
[2]=>
string(9) "corsa.png"
[3]=>
string(7) "cta.png"
[4]=>
string(9) "neons.png"
}
Added:
If a valid JSON string is to be generated from the specified string, this can also be done with a regular expression.
The algorithm also works without changes with keys other than 'src' and 'id'.
$jsonStr = '['.preg_replace('~\w+(?=:)~','"$0"', $str).']';
Or you can just use Regex:
(?<=")[^\\\/\:\*\?\"\<\>\|]+\.(?:png|jpg|gif)(?=")
Related
I am working a Rightmove BLM file and converting it into an array which is working fine.
However, the images are stored in sequential element nodes MEDIA_IMAGE_00, 01, 02 etc..
I am wondering if someone can advise me the best way to loop though those sequential elements using a wildcard or similar MEDIA_IMAGE_* for example.
Example of struture:
[MEDIA_IMAGE_00] => 003436_RX78401_IMG_00.jpg
[MEDIA_IMAGE_TEXT_00] =>
[MEDIA_IMAGE_01] => 003436_RX78401_IMG_01.jpg
[MEDIA_IMAGE_TEXT_01] =>
[MEDIA_IMAGE_02] => 003436_RX78401_IMG_02.jpg
[MEDIA_IMAGE_TEXT_02] =>
[MEDIA_IMAGE_03] => 003436_RX78401_IMG_03.jpg
Many Thanks!
The easiest solution might be:
foreach($array as $key=>$image)
{
if(str_contains($key, 'MEDIA_IMAGE_'))
{
//$image is your filename for the current image
}
}
But you can use RegEx instead.
In this case you just change the condition of the if to something like:
preg_match('/MEDIA_IMAGE_\d\d/', $key) === 1
You can use array_filter() in combination with an own filter-function.
Example
$inputArray['MEDIA_IMAGE_00'] = '003436_RX78401_IMG_00.jpg';
$inputArray['MEDIA_IMAGE_TEXT_00'] = '';
$inputArray['MEDIA_IMAGE_01'] = '003436_RX78401_IMG_01.jpg';
$inputArray['MEDIA_IMAGE_TEXT_01'] = '';
$inputArray['MEDIA_IMAGE_02'] = '003436_RX78401_IMG_02.jpg';
$inputArray['MEDIA_IMAGE_TEXT_02'] = '';
$inputArray['MEDIA_IMAGE_03'] = '003436_RX78401_IMG_03.jpg';
var_dump($inputArray);
/*
array(7) {
["MEDIA_IMAGE_00"]=>
string(25) "003436_RX78401_IMG_00.jpg"
["MEDIA_IMAGE_TEXT_00"]=>
string(0) ""
["MEDIA_IMAGE_01"]=>
string(25) "003436_RX78401_IMG_01.jpg"
["MEDIA_IMAGE_TEXT_01"]=>
string(0) ""
["MEDIA_IMAGE_02"]=>
string(25) "003436_RX78401_IMG_02.jpg"
["MEDIA_IMAGE_TEXT_02"]=>
string(0) ""
["MEDIA_IMAGE_03"]=>
string(25) "003436_RX78401_IMG_03.jpg"
}
*/
$inputArray = array_filter($inputArray, function($key) {
return preg_match('/MEDIA_IMAGE_\d\d/', $key) === 1;
}, ARRAY_FILTER_USE_KEY);
var_dump($inputArray);
/*
array(4) {
["MEDIA_IMAGE_00"]=>
string(25) "003436_RX78401_IMG_00.jpg"
["MEDIA_IMAGE_01"]=>
string(25) "003436_RX78401_IMG_01.jpg"
["MEDIA_IMAGE_02"]=>
string(25) "003436_RX78401_IMG_02.jpg"
["MEDIA_IMAGE_03"]=>
string(25) "003436_RX78401_IMG_03.jpg"
}
*/
If you just want to filter out empty values, you can even use filter_array() without any custom function. See the documentation for more information.
Documentation
array_filter() in php documentation.
I need to get ID´s from url:
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID=1&ID=5&ID=24&ID=32
If i use $_GET['ID'] a still get only last ID value. I need to get all of them to array, or select.
Can anybody help me?
Use array syntax:
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID[]=1&ID[]=5&ID[]=24&ID[]=32
var_dump($_GET['ID']);
array(4) {
[0]=>
int(1)
[1]=>
int(5)
[2]=>
int(24)
[3]=>
int(32)
}
}
echo $_GET['ID'][2]; // 24
The format in the URL is wrong. The second "ID" is overwriting the first "ID".. use an array:
http://www.example.org/?id[]=1&id[]=2&id[]=3
In PHP:
echo $_GET['id'][0]; // 1
echo $_GET['id'][1]; // 2
echo $_GET['id'][2]; // 3
To get this you need to make ID as array and pass it in the URL
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID[]=1&ID[]=5&ID[]=24&ID[]=32
and this can be manipulated at the backend like this
$urls = $_GET['ID'];
foreach($urls as $url){
echo $url;
}
OR
An alternative would be to pass json encoded arrays
http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID=[1,2,24,32]
which can be used as
$myarr = json_decode($_GET['ID']); // array(1,2,24,32)
I recommend you to also see for this here.
http_build_query()
it's wrong but if you really want to do this
<?php
function getIds($string){
$string = preg_match_all("/[ID]+[=]+[0-9]/i", $string, $matches);
$ids = [];
foreach($matches[0] as $match)
{
$c = explode("=", $match);
$ids [] = $c[1];
}
return $ids;
}
// you can change this with $_SERVER['QUERY_STRING']
$url = "http://www.aaaaa/galery.php?position=kosice&kategory=Castles&ID=1&ID=5&ID=24&ID=32";
$ids = getIds($url);
var_dump($ids);
I'm trying to find out if there's any function that would split a string like:
keyword=flower|type=outdoors|colour=red
to array:
array('keyword' => 'flower', 'type' => 'outdoors', 'colour' => 'red')
At the moment I built a custom function, which uses explode to first split elements with the separator | and then each of those with assignment symbol =, but is there perhaps a native function which would do it out of the box by specifying the string separator?
The function I've written looks like this:
public static function splitStringToArray(
$string = null,
$itemDivider = '|',
$keyValueDivider = '='
) {
if (empty($string)) {
return array();
}
$items = explode($itemDivider, $string);
if (empty($items)) {
return array();
}
$out = array();
foreach($items as $item) {
$itemArray = explode($keyValueDivider, $item);
if (
count($itemArray) > 1 &&
!empty($itemArray[1])
) {
$out[$itemArray[0]] = $itemArray[1];
}
}
return $out;
}
$string = "keyword=flower|type=outdoors|colour=red";
$string = str_replace('|', '&', $string);
parse_str($string, $values);
$values=array_filter($values); // Remove empty pairs as per your comment
print_r($values);
Output
Array
(
[keyword] => flower
[type] => outdoors
[colour] => red
)
Fiddle
Use regexp to solve this problem.
([^=]+)\=([^\|]+)
http://regex101.com/r/eQ9tW8/1
The issue is that your chosen format of representing variables in a string is non-standard. If you are able to change the | delimiter to a & character you would have (what looks like) a query string from a URL - and you'll be able to parse that easily:
$string = "keyword=flower&type=outdoors&colour=red";
parse_str( $string, $arr );
var_dump( $arr );
// array(3) { ["keyword"]=> string(6) "flower" ["type"]=> string(8) "outdoors" ["colour"]=> string(3) "red" }
I would recommend changing the delimiter at the source instead of manually replacing it with replace() or something similar (if possible).
In the example below $list is an array created by user input earlier in the code, and some slots the user has input nothing. I want to skip the empty items, so the commas aren't created in the output.
$list = array("first", "second", "", "", "fifth", "sixth", "", "");
foreach ($list as $each){$places .= $each . ",";}
results
first,second,,,fifth,sixth,,,
result I want
first,second,fifth,sixth
Got a solution. It looks like this:
$list = array_filter($list);
$places .= implode (",",$list);
To ignore the empty values, you can use
$list = array_filter($list);
Results
Array
(
[0] => first
[1] => second
[4] => fifth
[5] => sixth
)
Source: Mark
array_filter, when passed no second parameter, will remove any empty entries. From there you can proceed as normal:
foreach (array_filter($list) as $each){
$places .= $each . ',';
}
Though you can also use implode if you're just turning it in to a CSV:
$places .= implode(',', array_filter($list));
Side Note Though in this case array_filter may work, it is worth noting that this removes entries that result in a "falsy" result. That is to say:
$list = array_filter(array('foo','0','false',''));
// Result:
// array(2) {
// [0]=>
// string(3) "foo"
// [2]=>
// string(5) "false"
// }
So be careful. If the user could potentially be entering in numbers, I would stick with comparing empty. Alternatively you can use the second parameter of array_filter to make it more explicit:
function nonEmptyEntries($e)
{
return ((string)$e) !== '';
}
$list = array_filter($list, 'nonEmptyEntries');
// result:
//array(3) {
// [0]=>
// string(3) "foo"
// [1]=>
// string(1) "0"
// [2]=>
// string(5) "false"
//}
(Note that the 0 entry is kept, which differs from a blanket array_filter)
I have string data
$pages = "mangaName=&authorArtist=asdas123s&genres=sn&genres[23]=on&genres[29]=on&status=&chrome=&submit=+";
function get_h1($file){
$h1tags = preg_match_all('/\[(\w*)\]/is',$file,$patterns);
$res = array();
array_push($res,$patterns[2]);
array_push($res,count($patterns[2]));
return $res;
}
i want get number on genres[23] , genres[29]
[0] => 23
[1] => 29
$pages = "mangaName=&authorArtist=asdas123s&genres=sn&genres[23]=on&genres[29]=on&status=&chrome=&submit=+";
parse_str($pages, $parsed);
var_dump(array_keys($parsed['genres'])); // array(2) { [0]=> int(23) [1]=> int(29) }
zerkms' answer is the right one, but if you really want to use regexp, change yours with this one:
preg_match_all('/\[(\w*?)\]/is',$file,$patterns);
note the non-greedy __^