简体   繁体   中英

Capitalize First Letter Of Each Word except for URLs

Can someone tell me please how to do this:

Input:

hello http://DOMAIN.com/asdakdjk.php?asd=231&adsj=23 u.s. nicely done!

Result:

Hello http://DOMAIN.com/asdakdjk.php?asd=231&adsj=23 U.S. Nicely Done!

Including words in separated by '.'if possible such as in US

Thanks

try this:

<?php

function capitalizeNonURLs($input)
{
    preg_match('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', $input, $matches);
    $url = $matches[1];

    $temp = ucwords($input);
    $output = str_ireplace($url, $url, $temp);

    return $output;
}

$str = "hello http://domain.com/asdakdjk.php?asd=231&adsj=23 u.s. nicely done!";
echo capitalizeNonURLs($str);

Keep in mind that this function does not handle abbreviations (it won't change usa to USA). Country codes can be handled in several different ways. One is to make a hashmap of country codes and replace them or use regular expression for that as well.

To keep urls lower:

$strarray = explode(' ',$str);
for($i=0;$i<count($strarray))
{
if(substr($strarray[$i],0,4)!='http')
{
    $strarray[$i] = ucfirst($strarray[$i])
}
}

$new_str = implode('',$strarray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM