I need to convert a string to camel case, it's easy by using:
mb_convert_case($str, MB_CASE_TITLE, "UTF-8")
But what if string contains non-alphanumeric characters:
$str = 'he said "hello world"';
echo mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
Result is:
He Said "hello World"
But I need:
He Said "Hello World"
How can we handle this?
tHanks
With a regular expression.
If you are only going to work with non-accented latin characters, it can be as simple as
$str = 'he said "hello WORLD"';
echo preg_replace('/\b([a-z])/e', 'strtoupper(\'$1\')', strtolower($str));
This matches any lowercase unaccented latin letter that is preceded by a word boundary. The letter is replaced with its uppercase equivalent.
If you want this to work with other languages and scripts as well, you will have to get fancy:
$str = 'he said "καλημέρα ΚΌΣΜΕ"'; // this has to be in UTF-8
echo preg_replace('/(?<!\p{L})(\p{Ll})/eu',
'mb_convert_case(\'$1\', MB_CASE_UPPER, \'UTF-8\')',
mb_convert_case($str, MB_CASE_LOWER, 'UTF-8'));
To grok this you need to refer to the Unicode functionality of PCRE, and note that I have added the u modifier to preg_replace. This matches any unicode letter that has an uppercase equivalent (with the pattern \p{Ll}), provided that it is not preceded by any other letter (negative lookbehind with the pattern \p{L}). It then replaces it with the uppercase equivalent.
See it in action.
Update: It looks like you intend to consider only whitespace as word boundaries. This can be done with the regular expressions
(?<=\s|^)([a-z])
(?<=\s|^)(\p{Ll})
Try something like this (according to PHP.net comments)
$str = 'he said "hello world"';
echo preg_replace('/([^a-z\']|^)([a-z])/ie', '"$1".strtoupper("$2")', strtolower($str));
use manual! :D found on php.net
<?php
function ucwordsEx($str, $separator){
$str = str_replace($separator, " ", $str);
$str = ucwords(strtolower($str));
$str = str_replace(" ", $separator, $str);
return $str;
}
/*
Example:
*/
echo ucwordsEx("HELLO-my-NAME-iS-maNolO", "-");
/*
Prints: "Hello My Name Is Manolo"
*/
?>
For non-unicode characters following will work to convert a string to camel case:
preg_replace('/\b([a-z])/e', 'strtoupper("$1")', strtolower($str));
here is very simple code
echo ucwords('he said '.ucwords('"hello world"')) ;
output He Said Hello World
Related
Here is my code:
$txt = 'this is a text';
$word = 'is';
echo str_replace($word, '<b>'.$word.'</b>', $txt);
//=> th<b>is</b> <b>is</b> a text
As you see, my sub-string is is in example above and it matches just is part of this. While I need to select the whole of word. So this is expected result:
//=> <b>this</b> <b>is</b> a text
So I need to check both left and right side of the sub-string and match everything until either first of string ^ or end of string $ or white spage \s.
How can I do that?
You can use preg_replace to achieve that with Regex
http://php.net/manual/en/function.preg-replace.php
If you want to match a substring of a word as well as the word itself you can check for any word characters around the word your looking for like so:
$re = '/(\w*is\w*)/';
$str = 'this is a text';
$subst = '<b>$1<b>';
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
This will give you:
<b>this<b> <b>is<b> a text
Use a regular expression with word boundary anchors:
$regex = '/\b(\p{L}*' . preg_quote($word, '/') . '\p{L}*)\b/u';
echo preg_replace($regex, '<b>$1</b>', $txt);
where \p{L} stands for a Unicode letter (see Unicode character classes). If Unicode is not supported, replace \p{L} with \S (non-space character), for example.
Output
<b>this</b> <b>is</b> a text
I have a string like this:
$string = 'Hello k-on! Lorem Ipsum! Lorem.';
I want to get the first word that is followed by an exclamation-mark. So in the example above, it should be:
$word = 'k-on';
I'm lost as to what's the appropriate approach to take. Maybe a regex solution?
If you need to only support ASCII letter words, you can use
/\b[a-z]+(?:-[a-z]+)*!/i
See regex demo
If you plan to support Unicode, use \p{L}:
/\b\p{L}+(?:-\p{L}+)*!/u
See another regex demo
Here is the pattern explanation:
\b - a word boundary (the previous character must be a non-word one or the beginning of the string)
\p{L}+ - 1 or more Unicode characters (or ASCII if [a-zA-Z] is used)
(?:-\p{L}+)* - zero or more sequences of:
- - a literal hyphen
\p{L}+ - 1 or more Unicode characters (or ASCII if [a-zA-Z] is used)
! - a literal ! symbol
PHP demo:
$re = '/\b\p{L}+(?:-\p{L}+)*!/u';
$str = "Hello k-ąn! Lorem Ipsum! Lorem.";
preg_match($re, $str, $match);
print_r($match);
I think this might do what you're looking for. Basically split the string into words, look for the first word that ends in '!', do whatever then break out of the loop:
$string = 'Hello k-on! Lorem Ipsum! Lorem.';
arry = explode(" ", $string);
foreach ($arry as $word) {
if (substr($word,-1) == "!") {
do something ...
break;
}
}
$string = 'Hello k-on! Lorem Ipsum! Lorem.';
preg_match('/[A-Za-z0-9-]+!/', $string, $match);
$yourWord = str_replace("!", "", $match[0]); //prints k-on
obviously, the Solution for the requirement is RegExp, here i used a simple expression which allows AlphaNumeric String, exceptionally allowing hyphen(-) as well. use of preg_match matches the pattern into the string and returns the first matching keyword, which in your case is k-on! and used str_replace in order to take out the exclamation from the returned string.
know more about preg_match : http://php.net/manual/en/function.preg-match.php
I have a string with all letters capitalized. I'm using the ucwords() and the mb_strtolower() functions to capitalize only the first letter of a string. But I'm having some problems when the first letter of a word have a accent. For example:
ucwords(mb_strtolower('GRANDE ÁRVORE')); //outputs 'Grande árvore'
Why the first letter of the second word is not being capitalized? What can I do to solve this?
ucwords is one of the core PHP functions which is blissfully oblivious to non-ASCII or non-Latin-1 encodings.* For handling multibyte strings and/or non-ASCII strings, you should use the multibyte aware mb_convert_case:
mb_convert_case($str, MB_CASE_TITLE, 'UTF-8')
// your string encoding here --------^^^^^^^
* I'm not entirely sure whether it works only with ASCII or at least with Latin-1, but I wouldn't even bother to find out.
If you're looking to only capitalize the first letter only, here's a way to achieve it :
$s = "économie collégiale"
mb_strtoupper( mb_substr( $s, 0, 1 )) . mb_substr( $s, 1 )
// output : Économie collégiale
ucwords doesn't recognize the accented character. Try using mb_convert_case.
$str = 'GRANDE ÁRVORE';
function ucwords_accent($string)
{
if (mb_detect_encoding($string) != 'UTF-8') {
$string = mb_convert_case(utf8_encode($string), MB_CASE_TITLE, 'UTF-8');
} else {
$string = mb_convert_case($string, MB_CASE_TITLE, 'UTF-8');
}
return $string;
}
echo ucwords_accent($str);
I have a text field in which user can enter any character he/she wants. But in server i have a string patter [a-z0-9][a-z0-9+.-]*, if any of the character in the value from the text box doesn't match the pattern, then i must remove that character from that string. How can i do that in php. is there any functions for that?
Thanks in advance.
Gowri Sankar
.. in PHP we use regular Expressions with preg_replace.
Here you have some help with examples...
http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/
this is what you need:
$new_text = preg_replace('#[^A-Za-z+.-0-9]#s','',$text);
Just use preg_replace with the allowed pattern negated.
For example, if you allow a to Z and spaces, you simply negate it by adding a ^ to the character class:
echo preg_replace('/[^a-z ]*/i', '', 'This is a String !!!');
The above would output: This is a String (without the exclamation marks).
So it's removing any character that is not a to Z or space, e.g. your pattern negated.
How about:
$string = 'A quick test &*(^&for you this should work';
$searchForThis = '/[^A-Za-z \s]/';
$replaceWithBlank = '';
echo preg_replace($searchForThis, $replaceWithBlank , $string);
Try this:
$strs = array('+abc123','+.+abc+123','abc&+123','#(&)');
foreach($strs as $str) {
$str = preg_replace('/(^[^a-z0-9]*)|([^a-z0-9+.-]*)/', '', $str);
echo "'",$str,"'\n";
}
Output:
'abc123'
'abc+123'
'abc+123'
''
str_replace('x','',$text);
I would like to replace just complete words using php
Example :
If I have
$text = "Hello hellol hello, Helloz";
and I use
$newtext = str_replace("Hello",'NEW',$text);
The new text should look like
NEW hello1 hello, Helloz
PHP returns
NEW hello1 hello, NEWz
Thanks.
You want to use regular expressions. The \b matches a word boundary.
$text = preg_replace('/\bHello\b/', 'NEW', $text);
If $text contains UTF-8 text, you'll have to add the Unicode modifier "u", so that non-latin characters are not misinterpreted as word boundaries:
$text = preg_replace('/\bHello\b/u', 'NEW', $text);
multiple word in string replaced by this
$String = 'Team Members are committed to delivering quality service for all buyers and sellers.';
echo $String;
echo "<br>";
$String = preg_replace(array('/\bTeam\b/','/\bfor\b/','/\ball\b/'),array('Our','to','both'),$String);
echo $String;
Result: Our Members are committed to delivering quality service to both buyers and sellers.
Array replacement list: In case your replacement strings are substituting each other, you need preg_replace_callback.
$pairs = ["one"=>"two", "two"=>"three", "three"=>"one"];
$r = preg_replace_callback(
"/\w+/", # only match whole words
function($m) use ($pairs) {
if (isset($pairs[$m[0]])) { # optional: strtolower
return $pairs[$m[0]];
}
else {
return $m[0]; # keep unreplaced
}
},
$source
);
Obviously / for efficiency /\w+/ could be replaced with a key-list /\b(one|two|three)\b/i.
You can also use T-Regx library, that quotes $ or \ characters while replacing
<?php
$text = pattern('\bHello\b')->replace($text)->all()->with('NEW');