VinoCoder
VinoCoder

Reputation: 1153

Get file name from the string using php

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"}

Upvotes: 0

Views: 63

Answers (3)

KodeFor.Me
KodeFor.Me

Reputation: 13511

<?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 iterate over 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
// )

Upvotes: 2

jspit
jspit

Reputation: 7683

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).']'; 

Upvotes: 1

BG20
BG20

Reputation: 1

Or you can just use Regex: (?<=")[^\\\/\:\*\?\"\<\>\|]+\.(?:png|jpg|gif)(?=")

Upvotes: 0

Related Questions