This question already has answers here:
How to capitalize first letter of first word in a sentence?
(7 answers)
Closed 6 years ago.
I have a function that make the character of every new sentence upper case, however, it's not working properly. It only works if the new word is right up against the punctuation mark, and not if there is a space after the punctuation mark. How would I fix this?
//****************************************************************
function ucAll($str) {
return preg_replace_callback('/(?<=^|[\.\?!])[^\.]/', function ($match) {
return strtoupper($match[0]);
}, $str);
} //end of function ucAll($str)
//****************************************************************
$string = "i dont' want to? why should i?";
$string = ucAll($string);
echo $string;
Result
I dont' want to? why should i?
Need Result
I dont' want to? Why should i?
Just add (\s)* in appropriate place of your regular expression
<?php
//****************************************************************
function ucAll($str) {
return preg_replace_callback('/(?<=^|[\.\?!])(\s)*[^\.]/', function ($match) {
return strtoupper($match[0]);
}, $str);
} //end of function ucAll($str)
//****************************************************************
$string = "i dont' want to? why should i?";
$string = ucAll($string);
echo $string;
Related
I have two functions in PHP, trimmer($string,$number) and toUrl($string). I want to trim the urls extracted with toUrl(), to 20 characters for example. from https://www.youtube.com/watch?v=HU3GZTNIZ6M to https://www.youtube.com/wa...
function trimmer($string,$number) {
$string = substr ($string, 0, $number);
return $string."...";
}
function toUrl($string) {
$regex="/[^\W ]+[^\s]+[.]+[^\" ]+[^\W ]+/i";
$string= preg_replace($regex, "<a href='\\0'>".trimmer("\\0",20)."</a>",$string);
return $string;
}
But the problem is that the value of the match return \\0 not a variable like $url which could be easily trimmed with the function trimmer().
The Question is how do I apply substr() to \\0 something like this substr("\\0",0,20)?
What you want is preg_replace_callback:
function _toUrl_callback($m) {
return "" . trimmer($m[0], 20) ."";
}
function toUrl($string) {
$regex = "/[^\W ]+[^\s]+[.]+[^\" ]+[^\W ]+/i";
$string = preg_replace_callback($regex, "_toUrl_callback", $string);
return $string;
}
Also note that (side notes wrt your question):
You have a syntax error, '$regex' is not going to work (they don't replace var names in single-quoted strings)
You may want to look for better regexps to match URLs, you'll find plenty of them with a quick search
You may want to run through htmlspecialchars() your matches (mainly problems with "&", but that depends how you escape the rest of the string.
EDIT: Made it more PHP 4 friendly, requested by the asker.
This question already has answers here:
Make all words lowercase and the first letter of each word uppercase
(3 answers)
Closed 1 year ago.
The ucwords function in PHP doesn't consider non-whitespace to be word boundaries. So, if I ucwords this-that, I get This-that. What I want is all words capitalized, such as This-That.
This is a straightforward function to do so. Anyone have suggestions to improve the runtime?
function ucallwords($s)
{
$s = strtolower($s); // Just in case it isn't lowercased yet.
$t = '';
// Set t = only letters in s (spaces for all other characters)
for($i=0; $i<strlen($s); $i++)
if($s{$i}<'a' || $s{$i}>'z') $t.= ' ';
else $t.= $s{$i};
$t = ucwords($t);
// Put the non-letter characters back in t
for($i=0; $i<strlen($s); $i++)
if($s{$i}<'a' || $s{$i}>'z') $t{$i} = $s{$i};
return $t;
}
My gut feeling is that this could be done in a regular expression, but every time I start working on it, it gets complicated and I end up having to work on other things. I forget what I was doing and I have to start over. What I'd really like to hear is that PHP already has a good ucallwords function that I can use instead.
Taken directly from ucwords manual:
By jmarois at ca dot ibm dot com
<?php
//FUNCTION
function ucname($string) {
$string =ucwords(strtolower($string));
foreach (array('-', '\'') as $delimiter) {
if (strpos($string, $delimiter)!==false) {
$string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
}
}
return $string;
}
?>
<?php
//TEST
$names =array(
'JEAN-LUC PICARD',
'MILES O\'BRIEN',
'WILLIAM RIKER',
'geordi la forge',
'bEvErly CRuSHeR'
);
foreach ($names as $name) { print ucname("{$name}\n"); }
//PRINTS:
/*
Jean-Luc Picard
Miles O'Brien
William Riker
Geordi La Forge
Beverly Crusher
*/
?>
You can add more delimiters in the for-each loop array if you want to handle more characters.
A regular expression is easy for this:
$s = 'this-that'; //Original string to uppercase.
$r = preg_replace('/(^|[^a-z])[a-z]/e', 'strtoupper("$0")', $s);
This assumes that $s is lower case. You can use a-zA-Z in the second line to match upper and lower case letters. Alternately, you can wrap $s in the second line with strtolower($s).
This question already has answers here:
How to Truncate a string in PHP to the word closest to a certain number of characters?
(30 answers)
Closed 8 years ago.
I am working on this piece of code that will take my string and make it 200 characters long and then after that remove the last white space so my string will look like this 'This is my' instead of 'This is my stri'
This is what I got thus far:
$description = substr($value['description'], 0, 200);
and now I want it to remove the last white space in the string. After googleing it, all I found was the php trim function, but nothing about removing the last one, just all..
any tips?
function mycoolstring($longstring)
{
$stringarray=array();
if(strlen($longstring)>=200){
$stringarray=explode(" ",substr($longstring,0,200));
}
else{
$stringarray=explode(" ",$longstring);
}
$output=stringarray[0];
for($i=1;$i<count($stringarray)-1;$i++;
{
$output.=" " . $stringarray[$i];
}
return $output;
}
echo mycoolstring($value['discription']);
This may be a weired logic but it should work. Anyone see errors please kindly tell me or edit it. :)
If you want it to make it 200 characters long but if you don't want last word to be only partial it should be something like that:
<?php
mb_internal_encoding('UTF-8');
$value['description'] = 'avbd wreiuui ewrwrewre';
$desiredLength = 8;
if (mb_strlen($value['description']) <= $desiredLength) {
$description = $value['description'];
}
else {
$description = mb_substr($value['description'], 0, mb_strpos($value['description'],' ',$desiredLength-1));
}
echo $description."<br />";
function firstXChars($string, $chars = 100) {
preg_match('/^.{0,' . $chars. '}(?:.*?)\b/iu', $string, $matches);
return $matches[0];
}
echo firstXChars($value['description'], 200);
Demo
This question already has an answer here:
How to decode something beginning with "\u" with PHP
(1 answer)
Closed 8 years ago.
I have one string:
"Hello\u00c2\u00a0World"
I would like convert in:
"Hello World"
I try :
str_replace("\u00c2\u00a0"," ","Hello\u00c2\u00a0World");
or
str_replace("\\u00c2\\u00a0"," ","Hello\u00c2\u00a0World");
but not work!
Resolve!
str_replace(chr(194).chr(160)," ","Hello\u00c2\u00a0World");
If you would like to remove \u.... like patterns then you can use this for example:
$string = preg_replace('/(\\\u....)+/',' ',$input);
You are most of the way there.
$stuff = "Hello\u00c2\u00a0World";
$newstuff = str_replace("\u00c2\u00a0"," ",$stuff);
you need to put the return from str_replace into a variable in order to do something with it later.
This should work
$str="Hello\u00c2\u00a0World";
echo str_replace("\u00c2\u00a0"," ",$str);
You may try this, taken from this answer
function replaceUnicode($str) {
return preg_replace_callback("/\\\\u00([0-9a-f]{2})/", function($m){ return chr(hexdec($m[1])); }, $str);
}
echo replaceUnicode("Hello\u00c2\u00a0World");
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: How to check if a string starts with a specified string?
I am struggling to create a function to check this string starting from start_to_date or not, below is my implement.
$string = 'start_to_date-blablablabla';
if(cek_my_str($string)){
echo "String is OK";
}
// tes again
$string2 = 'helloworld-blablablabla';
if(cek_my_str($string2)){
echo "String not OK";
}
function cek_my_str($str){
// how code to return true if $str is string which start with start_to_date
}
Thanx.
In this case the best thing to do is:
if(strpos($string, 'start_to_date') === 0) { ... }
strpos() checks if 'start_to_date' is on position 0 (beginning)
To do it with Regex, you would do:
return preg_match('/^start_to_date/', $str);
Key reference: http://www.regular-expressions.info/
However, the PHP Manual for preg_match states
Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.
By the way, you should look into unit testing: http://www.phpunit.de/manual/current/en/
This is a way of encapsulating exactly what you are doing in reusable tests.
how about:
function cek_my_str($str){
return preg_match('/^start_to_date/', $str)
}
function cek_my_str($str){
$find = 'start_to_date';
$substr = substr($str, 0, strlen($find));
if($substr == $find){
return true;
}else{
return false;
}
}