I would like to change a string in php from all upper case to normal cases. So that every sentence would start with an upper case and the rest would be in lower case.
Is there a simple way to do this ?
A simple way is to use strtolower to make the string lower case, and ucfirst to upper case the first char as follows:
$str=ucfirst(strtolower($str));
If the string contains multiple sentences, you'll have to write your own algorithm, e.g. explode on sentence separators and process each sentence in turn. As well as the first char, you might need some heuristics for words like "I" and any common proper nouns which appear in your text. E.g, something like this:
$sentences=explode('.', strtolower($str));
$str="";
$sep="";
foreach ($sentences as $sentence)
{
//upper case first char
$sentence=ucfirst(trim($sentence));
//now we do more heuristics, like turn i and i'm into I and I'm
$sentence=preg_replace('/i([\s\'])/', 'I$1', $sentence);
//append sentence to output
$str=$sep.$str;
$sep=". ";
}
Here's a function that will do it:
function sentence_case($s) {
$str = strtolower($s);
$cap = true;
for($x = 0; $x < strlen($str); $x++){
$letter = substr($str, $x, 1);
if($letter == "." || $letter == "!" || $letter == "?"){
$cap = true;
}elseif($letter != " " && $cap == true){
$letter = strtoupper($letter);
$cap = false;
}
$ret .= $letter;
}
return $ret;
}
Source:
http://codesnippets.joyent.com/posts/show/715
I don't know of any method that will do this automatically. You would probably have to write your own with rules that would take of special cases like the letter 'i' needing to be capitalized when it is on its own. You would also still miss out on the ability to capitalize things like people and place names.
Perfectly possible
$s = "THIS IS THE LINE I'M GOING TO WORK ON";
$s = ucfirst(strtolower($s));
echo $s; //This is the line I'm going to work on
If the string contains only 1 sentence then you could use:
$string = ucfirst(strtolower($string));
Point to keep in mind: Do not apply this to all input fields!
People with ALL CAPS initials in their names can get mighty annoyed if you turn "Mike DF King" into "Mike Df King"
cheers :)
Related
If one is experienced in PHP, then one knows how to find whole words in a string and their position using a regex and preg_match() or preg_match_all. But, if you're looking instead for a lighter solution, you may be tempted to try with strpos(). The question emerges as to how one can use this function without it detecting substrings contained in other words. For example, how to detect "any" but not those characters occurring in "company"?
Consider a string like the following:
"Will *any* company do *any* job, (are there any)?"
How would one apply strpos() to detect each appearance of "any" in the string? Real life often involves more than merely space delimited words. Unfortunately, this sentence didn't appear with the non-alphabetical characters when I originally posted.
I think you could probably just remove all the whitespace characters you care about (e.g., what about hyphenations?) and test for " word ":
var_dump(firstWordPosition('Will company any do any job, (are there any)?', 'any'));
var_dump(firstWordPosition('Will *any* company do *any* job, (are there any)?', 'any'));
function firstWordPosition($str, $word) {
// There are others, maybe also pass this in or array_merge() for more control.
$nonchars = ["'",'"','.',',','!','?','(',')','^','$','#','\n','\r\n','\t',];
// You could also do a strpos() with an if and another argument passed in.
// Note that we're padding the $str to with spaces to match begin/end.
$pos = stripos(str_replace($nonchars, ' ', " $str "), " $word ");
// Have to account for the for-space on " $str ".
return $pos ? $pos - 1: false;
}
Gives 12 (offset from 0)
https://3v4l.org/qh9Rb
<?php
$subject = "any";
$b = " ";
$delimited = "$b$subject$b";
$replace = array("?","*","(",")",",",".");
$str = "Will *any* company do *any* job, (are there any)?";
echo "\nThe string: \"$str\"";
$temp = str_replace($replace,$b,$str);
while ( ($pos = strpos($temp,$delimited)) !== false )
{
echo "\nThe subject \"$subject\" occurs at position ",($pos + 1);
for ($i=0,$max=$pos + 1 + strlen($subject); $i <= $max; $i++) {
$temp[$i] = $b;
}
}
See demo
The script defines a word boundary as a blank space. If the string has non-alphabetical characters, they are replaced with blank space and the result is stored in $temp. As the loop iterates and detects $subject, each of its characters changes into a space in order to locate the next appearance of the subject. Considering the amount of work involved one may wonder if such effort really pays off compared to using a regex with a preg_ function. That is something that one will have to decide themselves. My purpose was to show how this may be achieved using strpos() without resorting to the oft repeated conventional wisdom of SO which advocates using a regex.
There is an option if you are loathe to create a replacement array of non-alphabetical characters, as follows:
<?php
function getAllWholeWordPos($s,$word){
$b = " ";
$delimited = "$b$word$b";
$retval = false;
for ($i=0, $max = strlen( $s ); $i < $max; $i++) {
if ( !ctype_alpha( $s[$i] ) ){
$s[$i] = $b;
}
}
while ( ( $pos = stripos( $s, $delimited) ) !== false ) {
$retval[] = $pos + 1;
for ( $i=0, $max = $pos + 1 + strlen( $word ); $i <= $max; $i++) {
$s[$i] = $b;
}
}
return $retval;
}
$whole_word = "any";
$str = "Will *$whole_word* company do *$whole_word* job, (are there $whole_word)?";
echo "\nString: \"$str\"";
$result = getAllWholeWordPos( $str, $whole_word );
$times = count( $result );
echo "\n\nThe word \"$whole_word\" occurs $times times:\n";
foreach ($result as $pos) {
echo "\nPosition: ",$pos;
}
See demo
Note, this example with its update improves the code by providing a function which uses a variant of strpos(), namely stripos() which has the added benefit of being case insensitive. Despite the more labor-intensive coding, the performance is speedy; see performance.
Try the following code
<!DOCTYPE html>
<html>
<body>
<?php
echo strpos("I love php, I love php too!","php");
?>
</body>
</html>
Output: 7
I have some string:
It's not big deal
I want to change it to
It's not_big deal
So far, I try this code but return "undefined offset: $y"
function checkNegation($word){
$input = strtolower($word);
$split = preg_split('/\s+/', $input);
$length = count($split);
$neg = "NOT_";
for ($x=0; $x<$length; $x++){
if (preg_match("/\bNOT\b/i",$split[$x])){
$y=$x+1;
$split[$x] = "{$neg}{$split[$y]}";
unset($split[$y]);
}
}
$word = implode(" ",$split);
return $word;
}
can you help me? thank you :')
Why not just preg_replace?
$str = "It's not big deal";
echo preg_replace("/\b(not)\s+/i", "$1_", $str); // It's not_big deal
if you're using regex already, why do you need to break the string into array of words? you can just match "not" in it and replace it with "not_". why over-complicate things?
your program seems to be running fine. but it'll cause problem if the word "not" is the last word in the string. because in that case, $y will go out of array range.
I need to extract a substring (for instance 22 characters) but I need to ignore spaces when counting the number of characters. For example:
$para = "While still in high school I signed up to participate in amateur night at the Educational Alliance. I wanted to show my mother I had talent.";
Let's say I need to get the substring that contains the 22 first characters but without counting the spaces. substr doesn't work:
echo substr($para, 0, 22); // => While still in high sc
But I need to get
// => While still in high school
How can I do this?
^(?=((?>.*?\S){20}))
Try this.Grab the capture or group.See demo.
https://regex101.com/r/fM9lY3/42
This uses lookahead to capture 20 groups of any character and a non space character. Precisely,lookahead will search for groups ending with non space character.Because it is non greedy,it will search first such 20 groups.
you just need to provide a string and length you want to be extracted from that string and function will return that string of specified length(yes return string will have spaces in it, but spaces won't be included in string).
Here is snippet.
$para = "While still in high school I signed up to participate in amateur night at the Educational Alliance. I wanted to show my mother I had talent.";
function getString($str, $length){
$newStr = "";
$counter = 0;
$r = array();
for($i=0; $i<strlen($str); $i++)
$r[$i] = $str[$i];
foreach($r as $char){
$newStr .= $char;
if($char != " "){
$counter += 1;
}
//return string if length reached.
if($counter == $length){
return $newStr;
}
}
return $newStr;
}
echo getString($para, 20);
//output: While still in high scho
echo getString($para, 22);
//output: While still in high school
First, use str_replace() to create a string $parawithoutspaces that consists of $para, without the spaces, like so:
$parawithoutspaces=str_replace(" ", "", $para);
Then, use substr() get the first 20 characters of $parawithoutspaces like so:
print substr($parawithoutspaces, 0, 20);
Or, combining the two steps into one and eliminating the need for the intermediate variable $parawithoutspaces:
print substr(str_replace(" ", "", $para),0,20);
You can try this, it is my code, $result is final string you want :
$arr1 = substr( $string,0,20);
$arr1 = explode(" ",$arr1);
array_pop($arr1);
$result = implode(" ",$arr1);
I want to CaPiTaLiZe $string in php, don't ask why :D
I made some research and found good answers here, they really helped me.
But, in my case I want to start capitalizing every odd character (1,2,3...) in EVERY word.
For example, with my custom function i'm getting this result "TeSt eXaMpLe" and want to getting this "TeSt ExAmPlE".
See that in second example word "example" starts with capital "E"?
So, can anyone help me? : )
Well I would just make it an array and then put it back together again.
<?php
$str = "test example";
$str_implode = str_split($str);
$caps = true;
foreach($str_implode as $key=>$letter){
if($caps){
$out = strtoupper($letter);
if($out <> " ") //not a space character
$caps = false;
}
else{
$out = strtolower($letter);
$caps = true;
}
$str_implode[$key] = $out;
}
$str = implode('',$str_implode);
echo $str;
?>
Demo: http://codepad.org/j8uXM97o
I would use regex to do this, since it is concise and easy to do:
$str = 'I made some research and found good answers here, they really helped me.';
$str = preg_replace_callback('/(\w)(.?)/', 'altcase', $str);
echo $str;
function altcase($m){
return strtoupper($m[1]).$m[2];
}
Outputs: "I MaDe SoMe ReSeArCh AnD FoUnD GoOd AnSwErS HeRe, ThEy ReAlLy HeLpEd Me."
Example
Here's a one liner that should work.
preg_replace('/(\w)(.)?/e', "strtoupper('$1').strtolower('$2')", 'test example');
http://codepad.org/9LC3SzjC
Try:
function capitalize($string){
$return= "";
foreach(explode(" ",$string) as $w){
foreach(str_split($w) as $k=>$v) {
if(($k+1)%2!=0 && ctype_alpha($v)){
$return .= mb_strtoupper($v);
}else{
$return .= $v;
}
}
$return .= " ";
}
return $return;
}
echo capitalize("I want to CaPiTaLiZe string in php, don't ask why :D");
//I WaNt To CaPiTaLiZe StRiNg In PhP, DoN'T AsK WhY :D
Edited: Fixed the lack of special characters in the output.
This task can be performed without using capture groups -- just use ucfirst().
This is not built to process multibyte characters.
Grab a word character then, optionally, the next character. From the fullstring match, only change the case of the first character.
Code: (Demo) (or Demo)
$strings = [
"test string",
"lado lomidze needs a solution",
"I made some research and found 'good' answers here; they really helped me."
]; // if not already all lowercase, use strtolower()
var_export(preg_replace_callback('/\w.?/', function ($m) { return ucfirst($m[0]); }, $strings));
Output:
array (
0 => 'TeSt StRiNg',
1 => 'LaDo LoMiDzE NeEdS A SoLuTiOn',
2 => 'I MaDe SoMe ReSeArCh AnD FoUnD \'GoOd\' AnSwErS HeRe; ThEy ReAlLy HeLpEd Me.',
)
For other researchers, if you (more simply) just want to convert every other character to uppercase, you could use /..?/ in your pattern, but using regex for this case would be overkill. You could more efficiently use a for() loop and double-incrementation.
Code (Demo)
$string = "test string";
for ($i = 0, $len = strlen($string); $i < $len; $i += 2) {
$string[$i] = strtoupper($string[$i]);
}
echo $string;
// TeSt sTrInG
// ^-^-^-^-^-^-- strtoupper() was called here
I need to format the following number 0825632332 to this format +27 (0)82 563 2332.
Which combination of functions would work the best, should I use regular expressions or normal string functions to perform the re-formatting? And how?
I think using a regexp is the best way, maybe something like this :
$text = preg_replace('/([0-9])([0-9]{2})([0-9]{3})([0-9]{4})/', '+27 ($1) $2 $3 $4', $num);
Be aware that $num must be a string since your number starts with 0.
You can also use character class :
$text = preg_replace('/(\d)(\d{2})(\d{3})(\d{4})/', '+27 ($1) $2 $3 $4', $num);
Since you asked - non regex solution:
<?php
function phnum($s, $format = '+27 (.).. ... ....') {
$si = 0;
for ($i = 0; $i < strlen($format); $i++)
if ($format[$i] == '.')
$output[] = $s[$si++];
else
$output[] = $format[$i];
return join('',$output);
}
echo phnum('0825632332');
?>
Regex will work nicely, replace
(\d)(\d{2})(\d{3})(\d{4})
by
+27 (\1)\2 \3 \4
You can also perform string submatching if you want.