Akash Talele
Akash Talele

Reputation: 27

Capitalize last word of a string

i have following code which capitalize First name & Last name, But some user have names like : "Malou van Mierlo" or "Malou de Mierlo" i dont want the "van" or "de" to be capital. How do i manage these exceptions? I think i can be solved if i just capitalize the last word in the last name. but how ?

add_filter('woocommerce_checkout_posted_data', 'mg_custom_woocommerce_checkout_posted_data');
function mg_custom_woocommerce_checkout_posted_data($data){
  // The data posted by the user comes from the $data param. 
  // You would look for the fields being posted, 
  // like "billing_first_name" and "billing_last_name"

  if($data['billing_first_name']){
    /*
      From jAnE to Jane
    */
    $data['billing_first_name'] = strtolower($data['billing_first_name']);
      $data['billing_first_name'] = ucwords($data['billing_first_name']);
  }

  if($data['billing_last_name']){
    /*
      From DOe to Doe
    */
    $data['billing_last_name'] = strtolower($data['billing_last_name']);
      
    $data['billing_last_name'] = ucwords($data['billing_last_name']);
  }

  return $data;
}

Upvotes: 0

Views: 268

Answers (2)

S N Sharma
S N Sharma

Reputation: 1526

Try this

$a = explode(' ', 'MaLou van mIerlo');

$a[array_key_first($a)] = ucfirst(strtolower($a[array_key_first($a)]));
$a[array_key_last($a)] = ucfirst(strtolower($a[array_key_last($a)]));

$a = implode(' ', $a);

Upvotes: 1

Giacomo M
Giacomo M

Reputation: 4701

You can do it by splitting the string and capitalizing first and last words of the string.

With this code you split the string:

$words = preg_split('/\s+/', $string);
array_map(strtolower, $words); // From jAnE to jane

With this code you capitalize the first and the last words of the name, and return the result:

$words[0] = ucfirst($words[0]);
$words[count($words) - 1] = ucfirst($words[count($words) - 1]);
return implode(' ', $words);

Upvotes: 2

Related Questions