Solved

PHP split string into array

Posted on 2010-08-21
14
578 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 31

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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 109

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 109

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
 
LVL 31

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 31

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
designing in object programming 12 79
hosting images 4 30
MySql and Apache/PHP Error Reporting 2 28
mysqli_connect error on wamp but not on remote server 8 27
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
This article will show, step by step, how to integrate R code into a R Sweave document
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

809 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