Jump to content

[SOLVED] Split Name by Captial Letters


jesushax

Recommended Posts

$string = "JohnSmith";

$splitStringArray = preg_split('/([A-Z])/',$string,-1,PREG_SPLIT_NO_EMPTY+PREG_SPLIT_DELIM_CAPTURE);

$splitString = '';
for($i = 0; $i < count($splitStringArray); $i++) {
if (($i > 0) && (($i % 2) == 0)) $splitString .= ' ';
$splitString .= $splitStringArray[$i];
}

echo $splitString;

function addSpaces($str) {
  $tmp='';
  $len=strlen($str);
  for ($i=0;$i<$len;++$i) {
    $tmp.=($str[$i]>='A'&&$str[$i]<='Z'&&$i>0 ? ' ' : '').$str[$i];
  }
  return $tmp;
}

 

Not tested, off the top of my head.

 

EDIT: Changed || to &&

I just tested it and it works.

 

<?php
echo addSpaces('JoeBloggs');

function addSpaces($str) {
  $tmp='';
  $len=strlen($str);
  for ($i=0;$i<$len;++$i) {
    $tmp.=($str[$i]>='A'&&$str[$i]<='Z'&&$i>0 ? ' ' : '').$str[$i];
  }
  return $tmp;
}
?>

 

In my browser I got

Joe Bloggs

 

Did you see the edit I made after posting?

that didnt work :|

 

in dreamweaver PREG_SPLIT_NO_EMPTY+PREG_SPLIT_DELIM_CAPTURE);

 

didnt show up as an colour could something be wrong there?

Did you actually try running it, or simply take dreamweaver's non-higjlighting as a sign that it wouldn't work

yes i tested it regardless of dreamweavers non colouring, im not stupid lol

 

ah yes it did work :)

 

i had my functions.php include lower then the text i wanted to run the addSpaces function on

moved it to the top and its all good now

 

thankyou very much for your time

yes i tested it regardless of dreamweavers non colouring, im not stupid lol

 

ah yes it did work :)

In that case, be aware that it won't work with single letter words such as the A in Yesideez's example

JoeBloggsLikesToEatAPlatterOfFish

yes i tested it regardless of dreamweavers non colouring, im not stupid lol

 

ah yes it did work :)

In that case, be aware that it won't work with single letter words such as the A in Yesideez's example

JoeBloggsLikesToEatAPlatterOfFish

I think you'll find I tested it and it worked!!!

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.