Jump to content

Recommended Posts

Hello,

 

This has been causing me grief for hours!

 

I have a string like this -

 

"'something1','something2','1,2,3'"

 

I want to split or explode at the commas, without exploding the 1,2,3 part.

 

The values are user input so in fact could contain any characters.

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/75375-solved-delimiting-and-explode/
Share on other sites

Thanks for the reply.

 

I think that with your suggestion if the user included the characters ',' in the string then it would cause an undesired split.

 

I was thinking there might be a way of escaping commas like this -

 

something1,something2,1\,2\,3

 

but I cant figure out how to split only on the non-escaped commas.

 

by the way, the string is coming from GROUP_CONCAT in mysql.

Erm, if you're pulling data from a mysql table, which you're concatenating with the mysql query, only to then explode, what's the point? Why not cycle through the rows and do what you want to do with the data.

 

Secondly, as you mentioned, the proposed solution would run into troubles if there was a single quote contained inside the string - if this is an issue, then what about if the user places a comma inside the string?

 

Edit: As a final point, you can do it like this, using regular expressions:

 

<?php
$str = 'something1,something2,1\,2\,3';
$bits = split('[^\\],',$str);
print_r($bits);
?>

The ugly way:

 

<?php

$str = "'a1','a2','1,2,3'";
$str = substr($str,0,-1);
$str = substr($str,1);

$parts = explode("','", $str);
echo"<pre>"; print_r($parts); echo "</pre>";

?>

 

 

 

The nice way:

 

<?php

$str = "'a1','a2','1,2,3'";

preg_match_all("/'(.*?)(',|'$)/", $str, $matches);
echo"<pre>"; print_r($matches[1]); echo "</pre>";

?>

 

 

Orio.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.