How to uppercase first letter after a hyphen, ie Adam Smith-Jones - php

I'm looking for a way to uppercase the first letter/s of a string, including where the names are joined by a hyphen, such as adam smith-jones needs to be Adam Smith-Jones.
ucwords() (or ucfirst() if I split them into firstname, lastname) only does Adam Smith-jones

$string = implode('-', array_map('ucfirst', explode('-', $string)));

What do you think about the following code ?
mb_convert_case(mb_strtolower($value, "UTF-8"), MB_CASE_TITLE, "UTF-8");
Please note that this also handles accented characters (usefull for some languages such as french).

Is this ok ?
function to_upper($name)
{
$name=ucwords($name);
$arr=explode('-', $name);
$name=array();
foreach($arr as $v)
{
$name[]=ucfirst($v);
}
$name=implode('-', $name);
return $name;
}
echo to_upper("adam smith-jones");

Other way:
<?php
$str = 'adam smith-jones';
echo preg_replace("/(-)([a-z])/e","'\\1'.strtoupper('\\2')", ucwords($str));
?>

/**
* Uppercase words including after a hyphen
*
* #param string $text lower-case text
* #return string Upper-Case text
*/
function uc_hyphenated_words($text)
{
return str_replace("- ","-",ucwords(str_replace("-","- ",$text)));
}

<?php
// note - this does NOT do what you want - but I think does what you said
// perhaps you can modify it to do what you want - or we can help if you can
// provide a bit more about the data you need to update
$string_of_text = "We would like to welcome Adam Smith-jones to our 3rd, 'I am addicted to stackoverflow-posting' event.";
// both Smith-Jones and Stackoverflow-Posting should result
// may be wrong
$words = explode(' ',$string_of_text);
foreach($words as $index=>$word) {
if(false !== strpos('-',$word)) {
$parts = explode('-',$word);
$newWords = array;
foreach($parts as $wordIndex=>$part) {
$newWords[] = ucwords($part);
}
$words[$index] = implode('-',$newWords);
}
}
$words = implode(' ',$words);
?>
Something akin to this - untested - for the purposes of making sure I understand the question.

You can us 'ucwords' to capitalize all words at once, and 'implode' and 'explode' together, like this:
ucwords(implode(" ", explode("_", "my_concatinated_word_string")));

function capWords($string) {
$string = str_replace("-", " - ", $string);
$string = ucwords(strtolower($string));
$string = str_replace(" - ", "-", $string);
return $string;
}

Here is a simple function that can convert all the words in a string to title case:
function toTitleCase($string) {
return preg_replace_callback('/\w+/', function ($match) {
return ucfirst(strtolower($match[0]));
}, $string);
}

Related

remove - and make every letter after as capital in the string - PHP [duplicate]

I want to take a string like this: 'this-is-a-string' and convert it to this: 'thisIsAString':
function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
// Do stuff
return $string;
}
I need to convert "kebab-case" to "camelCase".
No regex or callbacks necessary. Almost all the work can be done with ucwords:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false)
{
$str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
if (!$capitalizeFirstCharacter) {
$str[0] = strtolower($str[0]);
}
return $str;
}
echo dashesToCamelCase('this-is-a-string');
If you're using PHP >= 5.3, you can use lcfirst instead of strtolower.
Update
A second parameter was added to ucwords in PHP 5.4.32/5.5.16 which means we don't need to first change the dashes to spaces (thanks to Lars Ebert and PeterM for pointing this out). Here is the updated code:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false)
{
$str = str_replace('-', '', ucwords($string, '-'));
if (!$capitalizeFirstCharacter) {
$str = lcfirst($str);
}
return $str;
}
echo dashesToCamelCase('this-is-a-string');
This can be done very simply, by using ucwords which accepts delimiter as param:
function camelize($input, $separator = '_')
{
return str_replace($separator, '', ucwords($input, $separator));
}
NOTE: Need php at least 5.4.32, 5.5.16
Overloaded one-liner, with doc block...
/**
* Convert underscore_strings to camelCase (medial capitals).
*
* #param {string} $str
*
* #return {string}
*/
function snakeToCamel ($str) {
// Remove underscores, capitalize words, squash, lowercase first.
return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $str))));
}
In Laravel use Str::camel()
use Illuminate\Support\Str;
$converted = Str::camel('foo_bar');
// fooBar
this is my variation on how to deal with it. Here I have two functions, first one camelCase turns anything into a camelCase and it wont mess if variable already contains cameCase. Second uncamelCase turns camelCase into underscore (great feature when dealing with database keys).
function camelCase($str) {
$i = array("-","_");
$str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
$str = preg_replace('#[^a-zA-Z0-9\-_ ]+#', '', $str);
$str = str_replace($i, ' ', $str);
$str = str_replace(' ', '', ucwords(strtolower($str)));
$str = strtolower(substr($str,0,1)).substr($str,1);
return $str;
}
function uncamelCase($str) {
$str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str);
$str = strtolower($str);
return $str;
}
lets test both:
$camel = camelCase("James_LIKES-camelCase");
$uncamel = uncamelCase($camel);
echo $camel." ".$uncamel;
I would probably use preg_replace_callback(), like this:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
return preg_replace_callback("/-[a-zA-Z]/", 'removeDashAndCapitalize', $string);
}
function removeDashAndCapitalize($matches) {
return strtoupper($matches[0][1]);
}
You're looking for preg_replace_callback, you can use it like this :
$camelCase = preg_replace_callback('/-(.?)/', function($matches) {
return ucfirst($matches[1]);
}, $dashes);
here is very very easy solution in one line code
$string='this-is-a-string' ;
echo str_replace('-', '', ucwords($string, "-"));
output ThisIsAString
Try this:
$var='snake_case';
$ucword= ucword($var,'_');
echo $ucword;
Output:
Snake_Case
remove _ with str_replace
str_replace('_','',$ucword); //SnakeCase
and result
$result='SnakeCase'; //pascal case
echo lcfirst('SnakeCase'); //snakeCase (camel case)
the important thing is the approach here I used snake case and camel case in the example
$string = explode( "-", $string );
$first = true;
foreach( $string as &$v ) {
if( $first ) {
$first = false;
continue;
}
$v = ucfirst( $v );
}
return implode( "", $string );
Untested code. Check the PHP docs for the functions im-/explode and ucfirst.
One liner, PHP >= 5.3:
$camelCase = lcfirst(join(array_map('ucfirst', explode('-', $url))));
The TurboCommons library contains a general purpose formatCase() method inside the StringUtils class, which lets you convert a string to lots of common case formats, like CamelCase, UpperCamelCase, LowerCamelCase, snake_case, Title Case, and many more.
https://github.com/edertone/TurboCommons
To use it, import the phar file to your project and:
use org\turbocommons\src\main\php\utils\StringUtils;
echo StringUtils::formatCase('sNake_Case', StringUtils::FORMAT_CAMEL_CASE);
// will output 'sNakeCase'
Here's the link to the method source code:
https://github.com/edertone/TurboCommons/blob/b2e015cf89c8dbe372a5f5515e7d9763f45eba76/TurboCommons-Php/src/main/php/utils/StringUtils.php#L653
function camelize($input, $separator = '_')
{
return lcfirst(str_replace($separator, '', ucwords($input, $separator)));
}
echo ($this->camelize('someWeir-d-string'));
// output: 'someWeirdString';
Try this ;)
$string = 'this-is-a-string';
$separator = '-';
$stringCamelize = str_replace(
$separator,
'',
lcfirst(
ucwords(
strtolower($string),
$separator
)
)
);
var_dump($stringCamelize); // -> 'thisIsAString'
Alternatively, if you prefer not to deal with regex, and want to avoid explicit loops:
// $key = 'some-text', after transformation someText
$key = lcfirst(implode('', array_map(function ($key) {
return ucfirst($key);
}, explode('-', $key))));
Another simple approach:
$nasty = [' ', '-', '"', "'"]; // array of nasty characted to be removed
$cameled = lcfirst(str_replace($nasty, '', ucwords($string)));
Many good solutions above, and I can provide a different way that no one mention before. This example uses array. I use this method on my project Shieldon Firewall.
/**
* Covert string with dashes into camel-case string.
*
* #param string $string A string with dashes.
*
* #return string
*/
function getCamelCase(string $string = '')
{
$str = explode('-', $string);
$str = implode('', array_map(function($word) {
return ucwords($word);
}, $str));
return $str;
}
Test it:
echo getCamelCase('This-is-example');
Result:
ThisIsExample
Some very good solutions here. I compiled them together for easy c&p
declare(strict_types=1);
/**
* convert kebab-case to PascalCase
*/
function kebabToPascal( string $str ): string {
return str_replace( ' ', '', ucwords( str_replace( '-', ' ', $str ) ) );
}
/**
* convert snake_case to PascalCase
*/
function snakeToPascal( string $str ): string {
return str_replace (' ', '', ucwords( str_replace( '_', ' ', $str ) ) );
}
/**
* convert snake_case to camelCase
*/
function snakeToCamel( string $str ): string {
return lcfirst( snakeToPascal( $str ) );
}
/**
* convert kebab-case to camelCase
*/
function kebabToCamel( string $str): string {
return lcfirst( kebabToPascal( $str ) );
}
echo snakeToCamel( 'snake_case' ). '<br>';
echo kebabToCamel( 'kebab-case' ). '<br>';
echo snakeToPascal( 'snake_case' ). '<br>';
echo kebabToPascal( 'kebab-case' ). '<br>';
echo kebabToPascal( 'It will BREAK on things-like_this' ). '<br>';
In Yii2 you can use yii\helpers\Inflector::camelize():
use yii\helpers\Inflector;
echo Inflector::camelize("send_email");
// outputs: SendEmail
Yii provides a lot of similar functions, see the Yii2 Docs.
function camelCase($text) {
return array_reduce(
explode('-', strtolower($text)),
function ($carry, $value) {
$carry .= ucfirst($value);
return $carry;
},
'');
}
Obviously, if another delimiter than '-', e.g. '_', is to be matched too, then this won't work, then a preg_replace could convert all (consecutive) delimiters to '-' in $text first...
If you use Laravel framework, you can use just camel_case() method.
camel_case('this-is-a-string') // 'thisIsAString'
Here is another option:
private function camelcase($input, $separator = '-')
{
$array = explode($separator, $input);
$parts = array_map('ucwords', $array);
return implode('', $parts);
}
$stringWithDash = 'Pending-Seller-Confirmation';
$camelize = str_replace('-', '', ucwords($stringWithDash, '-'));
echo $camelize;
output: PendingSellerConfirmation
ucwords second(optional) parameter helps in identify a separator to camelize the string.
str_replace is used to finalize the output by removing the separator.
Here is a small helper function using a functional array_reduce approach.
Requires at least PHP 7.0
private function toCamelCase(string $stringToTransform, string $delimiter = '_'): string
{
return array_reduce(
explode($delimiter, $stringToTransform),
function ($carry, string $part): string {
return $carry === null ? $part: $carry . ucfirst($part);
}
);
}
private function dashesToCamelCase($string)
{
$explode = explode('-', $string);
$return = '';
foreach ($explode as $item) $return .= ucfirst($item);
return lcfirst($return);
}
This works for me:
function camelCase($string){
$chunks = preg_split("/\s+|-|_/",$string);
$camel = "";
foreach ($chunks as $idx => $chunk){
if ($idx===0){
$camel = strtolower($chunk);
}else{
$camel .= ucfirst($chunk);
}
}
return $camel;
}
The shortest and most elegant solution would be:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
$result = join("", array_map("ucfirst", explode("-", $string)));
if ($capitalizeFirstCharacter === false) {
return lcfirst($result);
}
return $result;
}
One Line Option
echo str_replace(' ', '', lcfirst(ucwords(str_replace("_", " ", 'facebook_catalog_id_type'))));
//output: facebookCatalogIdType
Try this:
return preg_replace("/\-(.)/e", "strtoupper('\\1')", $string);
This is simpler :
$string = preg_replace( '/-(.?)/e',"strtoupper('$1')", strtolower( $string ) );

remove substring from string by entering first and last character php

How can i remove substring from string by entering first and last character of substring in php
For example in string "Hello my name is John" if i enter 'n' and 's' it should return "Hello my John"... Please Help
/**
* Process function.
* For lack of a better name.
*/
function process($f, $l, $subject)
{
return preg_replace(sprintf('/%s.*?%s/', preg_quote($f), preg_quote($l)), '', $subject);
}
$f = 'n';
$l = 's';
echo process($f, $l, 'Hello my last name is Doe and my first name is John');
Output:
Hello my last Doe at John
I added utility, but it is effectively the same as preg_replace('/n.*?s/', '', $subject).
with your string given:
$var = "Hello my name is John";
$sub = getSubString($var,"n","s");
echo $sub;
function getSubString($str,$start,$end) {
if(($pos1=strpos($str,$start))===false)
return $str; // not found
if(($pos2=strpos($str,$end,$pos1))===false)
return $str; // not found
return substr($str,0,$pos1).substr($str,$pos2+1);
}
results in:
Hello my John
You should get the position of the first and second letter and use strpos for the method substr
function my_Cut($string, $first_letter, $second_letter){
$pos[] = strpos($string, $first_letter);
$pos[] = strpos($string, $second_letter);
$result = substr($string, $pos[0] , -($pos[1]-$pos[0]-2));
return str_replace ($result, "", $string);
}
$string = "Hello my name is John";
echo my_Cut($string, "n", "s");
Something like this... I think.

Regular expression for finding multiple patterns from a given string

I am using regular expression for getting multiple patterns from a given string.
Here, I will explain you clearly.
$string = "about us";
$newtag = preg_replace("/ /", "_", $string);
print_r($newtag);
The above is my code.
Here, i am finding the space in a word and replacing the space with the special character what ever i need, right??
Now, I need a regular expression that gives me patterns like
about_us, about-us, aboutus as output if i give about us as input.
Is this possible to do.
Please help me in that.
Thanks in advance!
And finally, my answer is
$string = "contact_us";
$a = array('-','_',' ');
foreach($a as $b){
if(strpos($string,$b)){
$separators = array('-','_','',' ');
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/".$b."/", $sep, $string);
}
print_r($outputs);
}
}
exit;
You need to do a loop to handle multiple possible outputs :
$separators = array('-','_','');
$string = "about us";
$outputs = array();
foreach ($separators as $sep) {
$outputs[] = preg_replace("/ /", $sep, $string);
}
print_r($outputs);
You can try without regex:
$string = 'about us';
$specialChar = '-'; // or any other
$newtag = implode($specialChar, explode(' ', $string));
If you put special characters into an array:
$specialChars = array('_', '-', '');
$newtags = array();
foreach ($specialChars as $specialChar) {
$newtags[] = implode($specialChar, explode(' ', $string));
}
Also you can use just str_replace()
foreach ($specialChars as $specialChar) {
$newtags[] = str_replace(' ', $specialChar, $string);
}
Not knowing exactly what you want to do I expect that you might want to replace any occurrence of a non-word (1 or more times) with a single dash.
e.g.
preg_replace('/\W+/', '-', $string);
If you just want to replace the space, use \s
<?php
$string = "about us";
$replacewith = "_";
$newtag = preg_replace("/\s/", $replacewith, $string);
print_r($newtag);
?>
I am not sure that regexes are the good tool for that. However you can simply define this kind of function:
function rep($str) {
return array( strtr($str, ' ', '_'),
strtr($str, ' ', '-'),
str_replace(' ', '', $str) );
}
$result = rep('about us');
print_r($result);
Matches any character that is not a word character
$string = "about us";
$newtag = preg_replace("/(\W)/g", "_", $string);
print_r($newtag);
in case its just that... you would get problems if it's a longer string :)

PHP: Normalize a string

I want to normalize (so canonicalize) a string into the normal form for names:
First letter of the name is uppercase
The difficulty by this is now to follow this rule with second and third name.
My method:
public function namilize($string)
{
$strings = explode(' ', $string);
foreach ($strings as $string) {
$string = ucfirst(strtolower($string));
}
$string = implode(' ', $strings);
return $string;
}
Somehow the
$string = ucfirst(strtolower($string));
fails.
What do I have to correct?
Is there a better way?
Regards
EDIT:
Hi,
thank you all for all the comments and answers.
I found another "modern" method:
public function namilize($string)
{
$string = mb_convert_case($string, MB_CASE_TITLE, mb_detect_encoding($string));
}
When I now would additionally add some regex for Mc and O's than it would be complete :)
public function namilize($name) {
$name = strtolower($name);
$normalized = array();
foreach (preg_split('/([^a-z])/', $name, NULL, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $word) {
if (preg_match('/^(mc)(.*)$/', $word, $matches)) {
$word = $matches[1] . ucfirst($matches[2]);
}
$normalized[] = ucfirst($word);
}
return implode('', $normalized);
}
Note that this will work for names like John O'Brian, James McManus, etc. For other names with prefixes like McManus, simply add the prefix to the preg_match(). Obviously, this runs the possibility of false positives, but no method is going to be 100% foolproof.
You have to pass the $string by reference, note the &:
public function namilize($string)
{
$strings = explode(' ', $string);
foreach ($strings as &$string) {
$string = ucfirst(strtolower($string));
}
$string = implode(' ', $strings);
return $string;
}
Or use the function suggested by #thetaiko ucwords($string)
The $string inside the foreach will only store the last iteration (or the last name). This doesn't really matter though because the variable in the foreach is never used for output. The implode just undoes what you did with the explode so you will end up with the exact same output as the input. I changed the variable names to be more descriptive in this example:
function namilize($name_in)
{
$a_names = explode(' ', $name_in); //explode string into array
foreach ($a_names as $name) {
$a_fullname[] = ucfirst(strtolower($name)); //build array of proper case names
}
$string = implode(' ', $a_fullname); //convert array into string
return $string;
}

Uppercase the first character of each word in a string except 'and', 'to', etc

How can I make upper-case the first character of each word in a string accept a couple of words which I don't want to transform them, like - and, to, etc?
For instance, I want this - ucwords('art and design') to output the string below,
'Art and Design'
is it possible to be like - strip_tags($text, '<p><a>') which we allow and in the string?
or I should use something else? please advise!
thanks.
None of these are really UTF8 friendly, so here's one that works flawlessly (so far)
function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("and", "to", "of", "das", "dos", "I", "II", "III", "IV", "V", "VI"))
{
/*
* Exceptions in lower case are words you don't want converted
* Exceptions all in upper case are any words you don't want converted to title case
* but should be converted to upper case, e.g.:
* king henry viii or king henry Viii should be King Henry VIII
*/
$string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
foreach ($delimiters as $dlnr => $delimiter) {
$words = explode($delimiter, $string);
$newwords = array();
foreach ($words as $wordnr => $word) {
if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtoupper($word, "UTF-8");
} elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtolower($word, "UTF-8");
} elseif (!in_array($word, $exceptions)) {
// convert to uppercase (non-utf8 only)
$word = ucfirst($word);
}
array_push($newwords, $word);
}
$string = join($delimiter, $newwords);
}//foreach
return $string;
}
Usage:
$s = 'SÃO JOÃO DOS SANTOS';
$v = titleCase($s); // 'São João dos Santos'
since we all love regexps, an alternative, that also works with interpunction (unlike the explode(" ",...) solution)
$newString = preg_replace_callback("/[a-zA-Z]+/",'ucfirst_some',$string);
function ucfirst_some($match)
{
$exclude = array('and','not');
if ( in_array(strtolower($match[0]),$exclude) ) return $match[0];
return ucfirst($match[0]);
}
edit added strtolower(), or "Not" would remain "Not".
How about this ?
$string = str_replace(' And ', ' and ', ucwords($string));
You will have to use ucfirst and loop through every word, checking e.g. an array of exceptions for each one.
Something like the following:
$exclude = array('and', 'not');
$words = explode(' ', $string);
foreach($words as $key => $word) {
if(in_array($word, $exclude)) {
continue;
}
$words[$key] = ucfirst($word);
}
$newString = implode(' ', $words);
I know it is a few years after the question, but I was looking for an answer to the insuring proper English in the titles of a CMS I am programming and wrote a light weight function from the ideas on this page so I thought I would share it:
function makeTitle($title){
$str = ucwords($title);
$exclude = 'a,an,the,for,and,nor,but,or,yet,so,such,as,at,around,by,after,along,for,from,of,on,to,with,without';
$excluded = explode(",",$exclude);
foreach($excluded as $noCap){$str = str_replace(ucwords($noCap),strtolower($noCap),$str);}
return ucfirst($str);
}
The excluded list was found at:
http://www.superheronation.com/2011/08/16/words-that-should-not-be-capitalized-in-titles/
USAGE: makeTitle($title);

Categories