Solved

PHP split string into array

Posted on 2010-08-21
14
551 Views
Last Modified: 2012-05-10
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"]'
);
0
Comment
Question by:gwkg
  • 4
  • 4
  • 3
  • +2
14 Comments
 
LVL 27

Assisted Solution

by:yodercm
yodercm earned 150 total points
ID: 33494140
$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
 
LVL 30

Assisted Solution

by:Marco Gasi
Marco Gasi earned 50 total points
ID: 33494196
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
 
LVL 58

Accepted Solution

by:
cyberkiwi earned 200 total points
ID: 33494468
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
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 100 total points
ID: 33495131
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
 
LVL 27

Expert Comment

by:yodercm
ID: 33495223
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
 
LVL 58

Expert Comment

by:cyberkiwi
ID: 33495243
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
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33495434
@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
Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 30

Expert Comment

by:Marco Gasi
ID: 33496385
@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
 
LVL 27

Expert Comment

by:yodercm
ID: 33496565
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
 
LVL 30

Expert Comment

by:Marco Gasi
ID: 33496598
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
 
LVL 58

Expert Comment

by:cyberkiwi
ID: 33497193
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
 
LVL 27

Expert Comment

by:yodercm
ID: 33497641
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
 
LVL 58

Expert Comment

by:cyberkiwi
ID: 33497679
>> 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
 
LVL 31

Author Closing Comment

by:gwkg
ID: 33497918
Thanks everyone!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now