Jump to content

[SOLVED] Explode string


themistral

Recommended Posts

Hi guys,

 

I have a string in this format:

 

This is a String i Want to Explode

 

I want the string to be exploded at all the capital letters - but I want to retain the capital letters so I get 4 strings:

This is a

String i

Want to

Explode

 

I'm missing something really simple here...

 

Currently I have

split("[A-Z]",$string);

 

but this returns

 

his is a

tring i

ant to

xplode

 

Can anyone out there help me?  ;D

Link to comment
Share on other sites

That's just how split works. You don't get the values that you're splitting on. Just what's around/between them. I don't know if there is a function to do what you want. I don't know enough about regex to be able to write something. But you could possibly just go through looking for capital letters and then add from the beginning to that spot to an array.

Link to comment
Share on other sites

<?php
$str = "This is a String i Want to Explode";
$pattern = "/(.)([A-Z])/";
$replacement = "\\1\n\\2";
$new = explode("\n", preg_replace($pattern, $replacement, $str));

print_r($new);
?>

 

Gives you:

Array
(
    [0] => This is a 
    [1] => String i 
    [2] => Want to 
    [3] => Explode
)

 

I typed in "php split string on uppercase letter" and found this:

http://www.webmasterworld.com/php/3608725.htm

 

Then I changed it to work after testing it locally.

Link to comment
Share on other sites

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.