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
https://forums.phpfreaks.com/topic/106627-solved-explode-string/
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.

<?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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.