Solved

Array Handling in PHP

Posted on 2010-11-07
9
258 Views
Last Modified: 2013-12-12
I use this script to ensure surnames are 'propercase' in php/mysql
This script sets the first character as uppercase and the first character after an apostraphe to uppercase as well.
I'd like to add some additional checks.
For example I'd like to check for hyphenated names and double barrelled names
ie
jones-smith becomes Jones-Smith
and
SMITH JONES becomes Smith Jones
I suspect we need an array to manage the apostraphe, hyphen & space.
thanks
Michael


if (strstr($surname, '\'')) {
  // Divide the surname into multiple parts, divided by apostrophes
  $surnameDivided = explode('\'', $surname);
  // Capitalize the first letter of each "part" of the surname
  foreach ($surnameDivided as &$part) {
    $part = ucfirst(strtolower($part));
  }
  // Bring the surname together again, with apostrophes
  $surname = implode('\'', $surnameDivided);
}

// If there is not an apostrophe in the surname,
// capitalize the first letter as you normally would
else {
  $surname = ucfirst(strtolower($surname));
}
0
Comment
Question by:joomla
  • 3
  • 3
  • 3
9 Comments
 
LVL 8

Expert Comment

by:shanikawm
ID: 34082459
Try something like this. Not sure I got your idea correctly.

This prints,

Jones Smith | Johnes Smith | Jone'S Smith | Jones-Smith
<?php

$name="jones smith | JOHNES SMITH | jone's smith | jones-smith ";

echo preg_replace("/(\b|-|')([^\b])([^\b]*?)/e","'\\1'.strtoupper('\\2').'\\3'",strtolower($name)).PHP_EOL;

?>

Open in new window

0
 

Author Comment

by:joomla
ID: 34082469
Hi shanikawm:
what I'm trying to achieve is to update a set of records which may contain 10,000 records
examples of names might be

o'brien             ---------   O'Brien
barrett-o'reily   ---------   Barrett-O'Reily
smith jones     ----------   Smith Jones
burns               ---------   Burns
CROWTHER   ----------   Crowther

thanks


0
 
LVL 8

Expert Comment

by:shanikawm
ID: 34082491
Hi Joomla,

All your cases are working with my script. Try

$name="o'brien | barrett-o'reily | smith jones | burns | CROWTHER"
or one by one like $name=" barrett-o'reily", $name="barrett-o'reily"
0
 

Author Comment

by:joomla
ID: 34083095
Hi,
I may be misunderstanding your script
If I don't know what $name is, will the test work for names like o'connell and brook-jones

regards
M
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 8

Expert Comment

by:shanikawm
ID: 34083140
Hope following code wil be clear for you. I just wrote your code with one line in a different way. It works for apostraphe, hyphen & space.
<?php

$surname="o'connell";

$surname=preg_replace("/(\b|-|')([^\b])([^\b]*?)/e","'\\1'.strtoupper('\\2').'\\3'",strtolower($surname));

echo $surname.PHP_EOL;

?>



// or



<?php

$surname="brook-jones";

$surname=preg_replace("/(\b|-|')([^\b])([^\b]*?)/e","'\\1'.strtoupper('\\2').'\\3'",strtolower($surname));

echo $surname.PHP_EOL;

?>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34083890
Here is the REGEX, annotated.  As you can see from the last example, there is more to getting this right than just capitalizing words.  And there are names from many languages ported into English (like van de Graaf) that do not follow the rules you have set out for capitalization.
<?php // RAY_temp_names.php

error_reporting(E_ALL);

echo "<pre>";



$regex

= "/"             // START REGEX DELIMITER

. "(\b|-|')"      // GROUP 1 - LETTER FOUND AT WORD BOUNDARY, OR DASH, OR APOSTROPHE

. "([^\b])"       // GROUP 2 - LETTER STARTS ON WORD BOUNDARY

. "([^\b]*?)"     // GROUP 3 - LETTER STARTS ON WORD BOUNDARY, ZERO OR MORE CHARS, UNGREEDY

. "/"             // END REGEX DELIMITER

. "e"             // EVALUATE FOR REPLACEMENT

;



$repl

= "'\\1'"

. "."

. "strtoupper('\\2')" // THE UPPERCASE

. "."

. "'\\3'"

;



// TEST NAMES

$names = array

( "o'brien"

, "barrett-o'reily"

, "Barrett-O'Reily"

, "smith jones"

, "burns"

, "CROWTHER"

, "George W. Bush, III"

)

;



// SHOW THE WORK PRODUCTS

foreach ($names as $name)

{

    // $new = preg_replace("/(\b|-|')([^\b])([^\b]*?)/e","'\\1'.strtoupper('\\2').'\\3'",strtolower($name));



    $new = preg_replace($regex, $repl, strtolower($name));

    echo PHP_EOL . "$name $new";

}

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 125 total points
ID: 34084020
This was an earlier attempt on my part to formulate a good set of rules and exceptions for capitalization of English names.  HTH, ~Ray
<?php // RAY_capitalize_names.php

error_reporting(E_ALL);



// SOME TEST NAMES

$names = array

( "o'brien"

, "barrett-o'reily"

, "smith jones"

, "burns"

, "CROWTHER"

, "George w. bush, iiI"

, "RONALD    MCDONALD"

, "RONALD    MCDONALD-o'brien"

, "van De Graaff GeneratoR"

)

;



// TEST EACH CASE

foreach ($names as $name)

{

    echo "<br/>$name ";

    echo fixname($name);

}





// FUNCTION TO HANDLE NAMES

function fixname($name)

{

    // SPECIAL CASES FOR UPPER OR LOWER CASE DISPOSITION

    $uc = array  // UPPERCASE AFTER ANY OF THESE

    (" Mc"

    , "'"

    , "-"

    )

    ;



    $lc = array  // ALWAYS LOWER CASE

    ( "Van De "

    )

    ;



    $mc = array  // ALWAYS UPPER CASE

    ( 'Iii'

    )

    ;



    // REMOVE UNNECESSARY BLANKS

    $name = preg_replace('/\s\s+/', ' ', $name);



    // START WITH LOWER CASE AND UPPER FIRST

    $name = strtolower($name);

    $name = ucwords($name);



    // CHECK FOR KNOWN SPECIAL UPPER-CASES

    foreach ($uc as $dlm)

    {

        // FIX THE Mcdonald EXAMPLE, ETC

        $namex = explode($dlm, $name);

        foreach ($namex as $k => $v)

        {

            $namex[$k] = ucwords($v);

        }

    $name = implode($dlm, $namex);

    }



    // CHECK FOR KNOWN CONSTANT LOWER-CASES

    foreach ($lc as $dlm)

    {

        // FIX THE van de Graaff EXAMPLE

        $name = str_replace($dlm, strtolower($dlm), $name);

    }



    // CHECK FOR KNOW CONSTANT UPPERCASE

    foreach ($mc as $dlm)

    {

        // FIX THE Bush, III EXAMPLE

        $name = str_replace($dlm, strtoupper($dlm), $name);

    }

    // RETURN THE REPAIRED STRING

    return $name;

}

Open in new window

0
 

Author Closing Comment

by:joomla
ID: 34091851
My goodness Ray
excellent script
you don't do anything by half do you?

thanks
M
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34092194
Thanks for the points.  It's actually a fairly common question, so I have dealt with it a few times before.  Common rules of grammar get distorted a little bit when we have to deal with proper names.  Best regards, ~Ray
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Echo images using file system 2 30
php refresh button on the browser 2 36
Should I use subdomains or addon domains? 3 33
echo time from sql to input type="time" 9 17
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now