PHP split string into array

I have a string of shortcodes I'm trying to split.

I need to take this string

$code = '[tag url="sample.com" name="Sample" type="Test" image=".png"][tag url="sample2.com" name="Sample 2" type="Test 2" image=".png"][tag url="www3.sample.com" name="Sample 3" type="Test 3" image=".jpg"][tag url="google.com" name="Google" type="url" image=".png"]';

and change into this array

$code = array(
    '[tag url="sample.com" name="Sample" type="Test" image=".png"]',
    '[tag url="sample2.com" name="Sample 2" type="Test 2" image=".png"]',
    '[tag url="www3.sample.com" name="Sample 3" type="Test 3" image=".jpg"]',
    '[tag url="google.com" name="Google" type="url" image=".png"]'
);
LVL 31
gwkgAsked:
Who is Participating?
 
cyberkiwiConnect With a Mentor Commented:
Quite simple

$code = explode("[[", substr(str_replace("[", "[[[", $code),2));

For your convenience, this and the first 2 expert comments are all compared below.
The 2nd solution creates an array with an embedded array.
$code = '[tag url="sample.com" name="Sample" type="Test" image=".png"][tag url="sample2.com" name="Sample 2" type="Test 2" image=".png"][tag url="www3.sample.com" name="Sample 3" type="Test 3" image=".jpg"][tag url="google.com" name="Google" type="url" image=".png"]';
echo "<br><br><br>";
echo "<pre>";
$code1 = explode("[[", substr(str_replace("[", "[[[", $code),2));
var_dump($code1);

$regexp = "/\[.*?\]/";
$res = array();
preg_match_all($regexp, $code, $res);
var_dump($res);

$temparray=explode('[', $code);
for ($i=1;$i<count($temparray);$i++)
{
  $codearray[$i]='['.$temparray[$i];
}
var_dump($codearray);
echo "</pre>";

Open in new window

0
 
Cornelia YoderConnect With a Mentor ArtistCommented:
$code = '[tag url="sample.com" name="Sample" type="Test" image=".png"][tag url="sample2.com" name="Sample 2" type="Test 2" image=".png"][tag url="www3.sample.com" name="Sample 3" type="Test 3" image=".jpg"][tag url="google.com" name="Google" type="url" image=".png"]';

$temparray=explode('[', $code);
for ($i=1;$i<count($temparray);$i++)
{
  $codearray[$i]='['.$temparray[$i];
}
0
 
Marco GasiConnect With a Mentor FreelancerCommented:
You cal also use regular expressions:

<?php
$code = '[tag url="sample.com" name="Sample" type="Test" image=".png"][tag url="sample2.com" name="Sample 2" type="Test 2" image=".png"][tag url="www3.sample.com" name="Sample 3" type="Test 3" image=".jpg"][tag url="google.com" name="Google" type="url" image=".png"]';

$regexp = "/\[.*?\]/";

$res = array();

preg_match_all($regexp, $code, $res);

echo "<pre>";
var_dump($res);
echo "</pre>";
?>

Best regards
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
Ray PaseurConnect With a Mentor Commented:
Use explode() to break strings into arrays.
http://us3.php.net/manual/en/function.explode.php

There is a complementary function, predictably named "implode" that reconstructs strings from arrays.
<?php // RAY_temp_explode.php
error_reporting(E_ALL);
echo "<pre>";

// DEMONSTRATION STRING
$string_code = '[tag url="sample.com" name="Sample" type="Test" image=".png"][tag url="sample2.com" name="Sample 2" type="Test 2" image=".png"][tag url="www3.sample.com" name="Sample 3" type="Test 3" image=".jpg"][tag url="google.com" name="Google" type="url" image=".png"]';

// DEMONSTRATION ARRAY
$array_code = array(
    '[tag url="sample.com" name="Sample" type="Test" image=".png"]',
    '[tag url="sample2.com" name="Sample 2" type="Test 2" image=".png"]',
    '[tag url="www3.sample.com" name="Sample 3" type="Test 3" image=".jpg"]',
    '[tag url="google.com" name="Google" type="url" image=".png"]'
);

// A DELIMITER EQUAL TO THE OPEN-TAG VALUE
$dlm = '[tag ';

// EXPLODE THE STRING
$my_array = explode($dlm, $string_code);

// REMOVE THE EMPTY POSITION ZERO AND RESET THE KEYS
unset($my_array[0]);
$my_array = array_values($my_array);

// PUT THE DELIMITER BACK ONTO EACH OF THE ELEMENTS OF THE ARRAY
foreach ($my_array as $pointer => $element)
{
    $my_array[$pointer] = $dlm . $element;
}

// SHOW THE CREATED ARRAY
var_dump($my_array);

// TURN THE ARRAY BACK INTO A STRING BY IMPLODE WITH A NULL DELIMITER
$my_string = implode('', $my_array);

// SHOW THE CREATED STRING
var_dump($my_string);

// TEST FOR EQUALITY AND EQUIVALENCE TO SEE IF WE GOT WHAT WE WANT
var_dump($my_array  === $array_code);
var_dump($my_string === $string_code);

Open in new window

0
 
Cornelia YoderArtistCommented:
Good grief.  I gave the asker the exact solution he asked for in four simple understandable lines of code, 15 minutes after it was asked.  

Regular expressions??  18 and 43 line versions of my original answer??  Doesn't anyone believe in straightforward programming any more?
0
 
cyberkiwiCommented:
In case anyone missed the obvious, my solution is in one line.
No regular expressions and no mumbo jumbo, just string replacements and explode to array.

The 18-line block of code demonstrates that your version does indeed work, the regex version is returning the wrong array.
0
 
Ray PaseurCommented:
@yodercm: I don't dispute whether any of these versions worked -- except for my own, I have not tested them.  In my example, I built in a set of displays and tests to prove to myself whether the code had worked or not.  What I am doing here is providing a code example with comments to make it a useful teaching sample for @gwkg.

In a "real life" situation I would have more generalized programming including data validation.  And I would probably have it be a method you can call on the shortcodes object.

Best to all, ~Ray
0
 
Marco GasiFreelancerCommented:
@cyberkiwi You're totally right about my solution (and really don't understand why preg_match_all return an array embedded in another array...) However, I like your solution very, very mutch: a genial way to use simultaneusly three different functions to obtain a correct result! Thanks
0
 
Cornelia YoderArtistCommented:
LOL   "A genial way to use simultaneously three different functions"???   What is this, a class in obscurity?   I am old enough to remember the days when programmers would walk into my office, toss down a listing, and claim "I bet you can't figure out what this does!".   I thought we were past those days years ago ... :(

Do you think you get more points here by solutions of 20 lines that the asker "...can't figure out what this does!", even if it works?
0
 
Marco GasiFreelancerCommented:
I was not speaking with you... Anyway, I suggest you to relax your mind and to read more carefully what is clearly written: cyberkiwi solution is only one row, this one:

$code = explode("[[", substr(str_replace("[", "[[[", $code),2));

Good bye
0
 
cyberkiwiCommented:
I take Ray's advice that comments are good.
Maybe my code was too "obfuscated" since it has confounded php-sage yodercrm :)
$code = "[....][....][....][....]"

As simple explode by "[" would
(1) lose the "[" which needs to be added back per yoderCRM's code.
(2) introduce an extra element handled by both yoderCRM and Ray's codes.

replace "[" with "[[["   -->   $Code = "[[[....][[[....][[[....][[[....]"

This allows us to split on "[[" without losing the "[".
Now to deal with the first empty element.

substr     -->   $Code = "[....][[[....][[[....][[[....]"

The "[[" delimiters can now be used safely in explode to return the array required.

Open in new window

0
 
Cornelia YoderArtistCommented:
Cyberkiwi, attempts to insult me are useless.  I know you are a good programmer, and you know I am one.  

"Confounded" me, no.  Obfuscated a very simple problem, yes, and that's what I think was unnecessary.  

Whether you double the [ first then explode (as you did), or explode first, then replace the [ (as I did), it's the same basic solution.  

Pretend you are novice enough to have to ask how to do this, and then tell me which variation of my solution is easier to understand on first reading, mine or yours.  

I just think that too many "experts" like to give cutsy complex solutions to easy questions, to make it look harder than it is, especially when someone else has posted a perfect simple solution hours earlier.  Not just yours, but imagine a novice trying to understand a regular expressions solution to something that can be done with explode() and one simple string concatenation, ESPECIALLY when you asks for it in an array.

When a perfect working solution is already posted on a question, why add more complexity hours later?  Do you really think anyone has improved on the first solution?



@gwkg, be sure to give all of these people points, they must be desperate for them.  I don't need any, I was just answering your question in a way that you would understand and be able to implement easily.

Best of luck with your project.
0
 
cyberkiwiCommented:
>> Cyberkiwi, attempts to insult me are useless.

I certainly would hope so!  I wasn't trying to physically hurt your or make anything stick.
There was a bit of jest thrown in there... but my skills at humor pales miserably to programming expertise.

(Nitpick, but I didn't just double the [, I tripled it! Not that it matters)

Pretending that I am a novice, it would not be entirely obvious why your index starts at 1 when as a novice, one would see most PHP loops start at 0.  I might even think it was a mistype.  If I am a bit better than novice, then I might understand that and equally a series of 3 simple basic php functions.

Just IMHO
0
 
gwkgAuthor Commented:
Thanks everyone!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.