I want to display a user's initials using only the first letter of their first name and the first letter of their last name. (Test User = TU)
How can I achieve this result even if a user inputs a prefix or a middle name? (Mr. Test Middlename User = TU).
This is the code I have so far (but will display more than 2 letters depending on user input):
public function initials() {
$words = explode(" ", $this->name );
$initials = null;
foreach ($words as $w) {
$initials .= $w[0];
}
return strtoupper($initials);
}
There are too many variations, but this should capture the first and last names in a string that may or may not have a prefix or suffix that is terminated with a period:
public function initials() {
preg_match('/(?:\w+\. )?(\w+).*?(\w+)(?: \w+\.)?$/', $this->name, $result);
return strtoupper($result[1][0].$result[2][0]);
}
$result[1] and $result[2] are the first and last capture groups and the [0] index of each of those is the first character of the string.
See an Example
This does a pretty good job, however names with a space in it will only return the second portion, such as De Jesus will only return Jesus. You could add known modifiers for surnames like de, von, van etc. but good luck catching them all, especially since it gets even longer van de, van der, van den.
To extend it for non-English prefixes and suffixes you would probably want to define them and strip them out as some may not end in a period.
$delete = ['array', 'of prefixes', 'and suffixes'];
$name = str_replace($delete, '', $this->name);
//or just beginning ^ and end $
$prefix = ['array', 'of prefixes'];
$suffix = ['array', 'of suffixes'];
$name = preg_replace("/^$prefix|$suffix$/", '', $this->name);
You can use reset() and end() to achieve this
reset() rewinds array's internal pointer to the first element and returns the value of the first array element.
end() advances array's internal pointer to the last element, and returns its value.
public function initials() {
//The strtoupper() function converts a string to uppercase.
$name = strtoupper($this->name);
//prefixes that needs to be removed from the name
$remove = ['.', 'MRS', 'MISS', 'MS', 'MASTER', 'DR', 'MR'];
$nameWithoutPrefix=str_replace($remove," ",$name);
$words = explode(" ", $nameWithoutPrefix);
//this will give you the first word of the $words array , which is the first name
$firtsName = reset($words);
//this will give you the last word of the $words array , which is the last name
$lastName = end($words);
echo substr($firtsName,0,1); // this will echo the first letter of your first name
echo substr($lastName ,0,1); // this will echo the first letter of your last name
}
Related
I have a string similar to the following and would like to count the number of the characters after the last comma.
$test = "apple, orange, green, red";
$count = strlen($test);
echo "$count";
and it should return 3.
I have used the strlen command but it returns the length of the whole string.
Thank you for your help!
In this case you can use from following codes:
$test = "apple, orange, green, red";
$ex = explode(',',$test);
$ex = array_reverse($ex);
echo strlen(trim($ex[0]));
first convert your String to an array and reverse that and get length of 0 index.
<?php
$test = "apple, orange, green, red";
// Exploded string with ,(comman) and store as an array
$explodedString = explode(",", $test);
// with end() get last element
$objLast = end($explodedString);
// remove white space before and after string
$tempStr = trim($objLast);
//With strlen() get count of number of characters in string
$finalStringLen = strlen($tempStr);
print_r("Length of '".$tempStr."' is ".$finalStringLen);
?>
First, you have to explode the string with the comma(,) then store it into any variable. You have to pass the variable that you have used previously for storing exploded array value in END function because END function required any variable as a parameter. If you use END function and do something inside rather than passing the parameter you will get an error. After you have to trim value which is return from END function for removing useless space then after use strlen function for getting the exact count of last String.
$test = "apple, orange, green, red";
$t = explode(",",$test);
print_r(strlen(trim(end($t))));
$splitString = explode(',', $test);
echo strlen($splitString[count($splitString)-1]); //it will show length of characters of last part
I'm trying to make my own bad word filter, and it works great, exept when I have multiple words in a sentence. So now What it does is, it takes the values out of the database and then loops trugh it and must replace the ad words.
Let me say I have (in dutch) this sentence: Deze kanker zooi moet eens stoppen! Het is godverdomme altijd het zelfde zooitje.. These are the words that must been replaced in the database:
kanker and godverdomme.
So I have in my database:
Thats all good, exept when the 2 ords must been replaced, then it doesn't want to replace...
My helper function:
public static function Filter($value)
{
$badwords = DB::table('badwords')->get();
foreach ($badwords as $badword)
{
$replaced = str_ireplace($badword->bad_word, $badword->replacement, $value);
}
return $replaced;
}
Hope someone can help me :)
Kindest regards,
Robin
For each iteration in your foreach loop, you set the value of $replaced to whatever str_ireplace returns.
At the end of the function you will return a value where only the last bad word should have been replaced.
str_ireplace takes either a single string value or an array of string values to replace as first and second parameter which means that you instead could create two arrays, which you fill in theforeach loop and then run the str_ireplace after the loop, something like:
$words = [];
$replace = [];
foreach ($badwords as $badword) {
array_push($words, $badword->bad_word);
array_push($replace, $badword->replacement);
}
return str_ireplace($words, $replace, $value);
Consider the following array which holds all US stock tickers, ordered by length:
$tickers = array('AAPL', 'AA', 'BRK.A', 'BRK.B', 'BAE', 'BA'); // etc...
I want to check a string for all possible matches. Tickers are written with or without a "$" concatenated to the front:
$string = "Check out $AAPL and BRK.A, BA and BAE.B - all going up!";
All tickers are to be labeled like: {TICKER:XX}. The expected output would be:
Check out {TICKER:AAPL} and {TICKER:BRK.A} and BAE.B - all going up!
So tickers should be checked against the $tickers array and matched both if they are followed by a space or a comma. Until now, I have been using the following:
preg_replace('/\$([a-zA-Z.]+)/', ' {TICKER:$1} ', $string);
so I didn't have to check against the $tickers array. It was assumed that all tickers started with "$", but this only appears to be the convention in about 80% of the cases. Hence, the need for an updated filter.
My question being: is there a simple way to adjust the regex to comply with the new requirement or do I need to write a new function, as I was planning first:
function match_tickers($string) {
foreach ($tickers as $ticker) {
// preg_replace with $
// preg_replace without $
}
}
Or can this be done in one go?
Just make the leading dollar sign optional, using ? (zero or 1 matches). Then you can check for legal trailing characters using the same technique. A better way to go about it would be to explode your input string and check/replace each substring against the ticker collection, then reconstruct the input string.
function match_tickers($string) {
$aray = explode( " ", $string );
foreach ($aray as $word) {
// extract any ticker symbol
$symbol = preg_replace( '/^\$?([A-Za-z]?\.?[A-Za-z])\W*$/', '$1', $word );
if (in_array($symbol,$tickers)) { // symbol, replace it
array_push( $replacements, preg_replace( '/^\$?([A-Za-z]?\.?[A-Za-z])(\W*)$/', '{TICKER:$1}$2', $word ) );
}
else { // not a symbol, just output it normally
array_push( $replacements, $word );
}
}
return implode( " ", $replacements );
}
I think just a slight change to your regex should do the trick:
\$?([a-zA-Z.]+)
i added "?" in front of the "$", which means that it can appear 0 or 1 times
You can use a single foreach loop on your array to replace the ticker items in your string.
$tickers = array('AAPL', 'AA', 'BRK.A', 'BRK.B', 'BAE', 'BA');
$string = 'Check out $AAPL and BRK.A, BA and BAE.B - all going up!';
foreach ($tickers as $ticker) {
$string = preg_replace('/(\$?)\b('.$ticker.')\b(?!\.[A-Z])/', '{TICKER:$2}', $string);
}
echo $string;
will output
Check out {TICKER:AAPL} and {TICKER:BRK.A}, {TICKER:BA} and BAE.B -
all going up!
Adding ? after the $ sign will also accept words, i.e. 'out'
preg_replace accepts array as a pattern, so if you change your $tickers array to:
$tickers = array('/AAPL/', '/AA/', '/BRK.A/', '/BRK.B/', '/BAE/', '/BA/');
then this should do the trick:
preg_replace($tickers, ' {TICKER:$1} ', $string);
This is according to http://php.net/manual/en/function.preg-replace.php
I have some text inside $content var, like this:
$content = $page_data->post_content;
I need to slice the content somehow and extract the sentences, inserting each one inside it's own var.
Something like this:
$sentence1 = 'first sentence of the text';
$sentence2 = 'second sentence of the text';
and so on...
How can I do this?
PS
I am thinking of something like this, but I need somekind of loop for each sentence:
$match = null;
preg_match('/(.*?[?\.!]{1,3})/', $content, $match);
$sentence1 = $match[1];
$sentence2 = $match[2];
Ty:)
Do you need them in variables? Can't you use a array?
$sentence = explode(". ", $page_data->post_content);
EDIT:
If you need variables:
$allSentence = explode(". ", $page_data->post_content);
foreach($allSentence as $key => $val)
{
${"sentence". $key} = $val;
}
Assuming each sentence ends with full stop, you can use explode:
$content = $page_data->post_content;
$sentences = explode('.', $content);
Now your sentences can be accessed like:
echo $sentences[0]; // 1st sentence
echo $sentences[1]; // 2nd sentence
echo $sentences[2]; // 3rd sentence
// and so on
Note that you can count total sentences using count or sizeof:
echo count($sentences);
It is not a good idea to create a new variable for each sentence, imagine you might have long piece of text which would require to create that number of variables there by increasing memory usage. You can simply use array index $sentences[0], $sentences[1] and so on.
Assuming a sentence is delimited by terminating punctuation, optionally followed by a space, you can do the following to get the sentences in an array.
$sentences = preg_split('/[!?\.]\s?/', $content);
You may want to trim any additional spaces as well with
$sentences = array_map('trim', $sentences);
This way, $sentences[0] is the first, $sentences[1] is the second and so on. If you need to loop through them you can use foreach:
foreach($sentences as $sentence) {
// Do something with $sentence...
}
Don't use individually named variables like $sentence1, $sentence2 etc. Use an array.
$sentences = explode('.', $page_data->post_content);
This gives you an array of the "sentences" in the variable $page_data->post_content, where "sentences" really means sequences of characters between full stops. This logic will get tripped up wherever a full stop is used to mean something other than the end of a sentence (e.g. "Mr. Watson").
Edit: Of course, you can use more sophisticated logic to detect sentence boundaries, as you have suggested. You should still use an array, not create an unknown number of variables with numbers on the ends of their names.
I need a simple word filter that will kill a script if it detects a filtered word in a string.
say my words are as below
$showstopper = array(badword1, badword2, badword3, badword4);
$yourmouth = "im gonna badword3 you up";
if(something($yourmouth, $showstopper)){
//stop the show
}
You could implode the array of badwords into a regular expression, and see if it matches against the haystack. Or you could simply cycle through the array, and check each word individually.
From the comments:
$re = "/(" . implode("|", $showstopper) . ")/"; // '/(badword1|badword2)/'
if (preg_match($re, $yourmouth) > 0) { die("foulmouth"); }
in_array() is your friend
$yourmouth_array = explode(' ',$yourmouth);
foreach($yourmouth_array as $key=>$w){
if (in_array($w,$showstopper){
// stop the show, like, replace that element with '***'
$yourmouth_array[$key]= '***';
}
}
$yourmouth = implode(' ',$yourmouth_array);
You might want to benchmark this vs the foreach and preg_match approaches.
$showstopper = array('badword1', 'badword2', 'badword3', 'badword4');
$yourmouth = "im gonna badword3 you up";
$check = str_replace($showstopper, '****', $yourmouth, $count);
if($count > 0) {
//stop the show
}
A fast solution involves checking the key as this does not need to iterate over the array. It would require a modification of your bad words list, however.
$showstopper = array('badword1' => 1, 'badword2' => 1, 'badword3' => 1, 'badword4' => 1);
$yourmouth = "im gonna badword3 you up";
// split words on space
$words = explode(' ', $yourmouth);
foreach($words as $word) {
// filter extraneous characters out of the word
$word = preg_replace('/[^A-Za-z0-9]*/', '', $word);
// check for bad word match
if (isset($showstopper[$word])) {
die('game over');
}
}
The preg_replace ensures users don't abuse your filter by typing something like bad_word3. It also ensures the array key check doesn't bomb.
not sure why you would need to do this but heres a way to check and get the bad words that were used
$showstopper = array(badword1, badword2, badword3, badword4);
$yourmouth = "im gonna badword3 you up badword1";
function badWordCheck( $var ) {
global $yourmouth;
if (strpos($yourmouth, $var)) {
return true;
}
}
print_r(array_filter($showstopper, 'badWordCheck'));
array_filter() returns an array of bad words, so if the count() of it is 0 nothign bad was said