Using ucwords and explode to ignore hyphens and capitalise words in php

916 Views Asked by At

I am using this php code

    <title>Web Design <?php
    echo ucwords(array_shift(explode(".",$_SERVER['HTTP_HOST'])));
    ?>, Website Design</title>

to grab the subdomain (subdomain.domain.co.uk) which works great However - I want it to ignore the hyphen and capitalise the words for hyphenated subdomains i.e. sub-domain.domain.co.uk => Sub Domain

What do I have to alter my code to?

2

There are 2 best solutions below

4
On BEST ANSWER

Use str_replace('-', ' ', $subdomain) before calling ucwords to replace - with a space. For example:

<?php
$subdomain = array_shift(explode(".",$_SERVER['HTTP_HOST']));
echo ucwords(str_replace('-', ' ', $subdomain));
?>
0
On

Tried str_replace ?

<?php
  $domain = $_SERVER["HTTP_HOST"];
  $domain = explode( ".", $domain ); // split domain by comma
  $domain = array_shift( $domain ); // shift an element off the begginning of array
  $domain = str_replace( "-", " ", $domain ); // replace all occureance of '-' to space
  $domain = ucwords( $domain ); // uppercase the first character of words

  echo $domain;
?>