Web Hosting Talk







View Full Version : PHP: Find and explode string by capital letters


serversphere
07-02-2006, 12:15 PM
Here's one I can't seem to wrap my head around. I want to parse a given string and explode it by capital letters in PHP. Example:

I have "MustangBlueHeadlining", and want to separate out the words to be:

Mustang
Blue
Headlining

in a single string with the spaces included ("Mustang Blue Headlining") or an array...

The problem I'm having is a simple way to test if a char is cap or not. Can't find a built in function that does this on php.net. The only way I can think to do it is parse through the string char by char and compare each letter to a pre-set array of capital letters... Anyone ever done this? Easier way? Thanks!

Dark Light
07-02-2006, 12:50 PM
Try this:
<?php

$string = $_GET['string'];

$count = strlen($string);

$i = 0;
$ii = 0;

while($i < $count)
{
$char = $string{$i};
if(ereg("[A-Z]", $char, $val)){
$ii++;
$strings[$ii] .= $char;
} else {
$strings[$ii] .= $char;
}
$i++;
}

var_dump($strings);

?>

It will explode your $string based on capital letters, and put it in $strings[$i].
E.g.:
$strings:
array(3) { [1]=> string(7) "Mustang" [2]=> string(4) "Blue" [3]=> string(10) "Headlining" }

aonic
07-02-2006, 02:58 PM
<?php
$split2 = preg_split("/[A-Z]/", "MustangBlueHeadliningWhatHaxZomgHax", -1, PREG_SPLIT_NO_EMPTY);
$split = preg_split("/[a-z]/", "MustangBlueHeadliningWhatHaxZomgHax", -1, PREG_SPLIT_NO_EMPTY);
function getWord($index)
{
global $split, $split2;
return $split[$index].$split2[$index];
}

//example for display
for($e=(count($split)-1); $e != -1; $e--)
{
echo 'index[ '.$e.' ] = '.getWord($e).'<br />';
}
?>

maybe not the best way, but i like it!

csavencu
07-02-2006, 06:52 PM
<?
$string = "SomeTestString";
$list = split(",",substr(preg_replace("/([A-Z])/",',\\1',$string),1));
?>

Form1
07-02-2006, 08:54 PM
<?
$str="MustangBlueHeadlining";

preg_match_all('/[A-Z][^A-Z]*/',$str,$results);

?>

Take it easy,

Dave

serversphere
07-03-2006, 09:42 AM
<?
$str="MustangBlueHeadlining";

preg_match_all('/[A-Z][^A-Z]*/',$str,$results);

?>

Take it easy,

Dave

Easy being the key word... Thanks Dave, exactly what I was looking for! Thanks to others who posted as well. I was iterating through already but figured there was a simpler way, just couldn't think of it.