trying to cut off at the last character that's a space - php

I need to find out where the last character in the string is where the charachter is a space, and cut it off there. This is the function I'm using, but there seems to be something wrong with the if statement, but I can't figure out what. There is certainly a space in the $text-string.
Let's say I have a string "Hey, my name is Joh". Then it has to be shortened to "Hey, my name is ".
$checkLastChar = false;
$text = $line[2];
while($checkLastChar != true){
for($i = 1; $i <= strlen($text); $i++)
{
if($text[strlen($tekst) - $i] == " ") {
$checkLastChar = true;
$text = substr($text, 1, strlen($text) - $i);
}
}
}

substr($string, 0, strrpos($string, ' '));

Why don't you use rtrim()?
update
Based on the clarification a solution like Nate's seems to be more appropriate.

Have you ever considered using trim()? It strips the spaces from beginning AND end.
Example:
echo trim(' Hello my name is Matt. ');

Try this:
<?php
$str = "dsajhc \tsjdtgsd "; // string with whitespaces
$str = preg_replace( '/(\s+.*)/i', '', $str ); // remove everything after whitespace
?>
Hope it helps.

Related

How to replace a letter in a sea of recurring letter with php?

$aEnd = "123/123/432/Omeagle";
$aEnd = str_replace("/", "-", $aEnd); // Output: "123-123-432-Omeagle"
$finda = strpos($aEnd, "-");
$countHypen = 0;
$wordLength = 0;
foreach($aEnd as $word){
$wordLength += 1;
if($word == "-"){
$countHypen +=1;
if($countHypen == $finda){
break;
}
}
$aEnd = substr_replace($aEnd," ",$wordLength, 1);
}
Problem
As you can see from the code above, I am trying to replace the fourth occurrence of the word but the way I did it is super duper inefficient as I have to run this portion quite a lot of times plus the length of the $aEnd is always changing.
Question
Is there any better way? Thanks.
Expecting Output
From: 123/123/432/Omeagle
To: 123-123-432 Omeagle
preg_replace should work here, using the following pattern:
\/(?=.*\/)
This will target any path separator which is not the final one, and then we replace it with dash. After this, we make a single call to str_replace to replace the final remaining path separator with a space.
$aEnd = "123/123/432/Omeagle";
$output = preg_replace("/\/(?=.*\/)/", "-", $aEnd);
$output = str_replace("/", " ", $output);
echo $output;
This prints:
123-123-432 Omeagle
You can do all the replacements in one call to preg_replace, replacing / that are followed by another / (/(?=.*/)) with -, and a / not followed by / (/(?=[^/]*$)) with a space:
$aEnd = "123/123/432/Omeagle";
$aEnd = preg_replace(array('#/(?=.*/)#', '#/(?=[^/]*$)#'), array('-', ' '), $aEnd);
echo $aEnd;
Output:
123-123-432 Omeagle
Demo on 3v4l.org

PHP hide part of string

I'm searching for the most elegant way in PHP to hide a string (for example an username).
For example, usernames should be shown as:
tim will be shown as: t*m
So the username itself is not completely "cryptically", but no one can guess their login name or at least not for sure.
You can use preg_replace:
$string = 'usernameTest';
echo preg_replace("/(?!^).(?!$)/", "*", $string); // u**********t
(?!^) Checks if the character is not the first character in the string.
. matches any character
(?!$) Checks if the character is not the last character in the string.
Hope this helps.
You can use the following regex along with preg_replace function like as
(^.|.$)(*SKIP)(*F)|(.)
Example
$your_string = "Narendra";
echo preg_replace("/(^.|.$)(*SKIP)(*F)|(.)/","*",$your_string);
Output :
N******a
Explanation of Regex:
(^.|.$) This'll capture the first and last alphabet of the word
(*SKIP)(*F) This'll skip the above captured words
|(.) Over here rest of the alphabets'll be captured and can be replaced further with your character i.e. * over here
Demo
Try:
function get_starred($str) {
$len = strlen($str);
return substr($str, 0, 1).str_repeat('*', $len - 2).substr($str, $len - 1, 1);
}
$myStr = 'YourName';
echo get_starred($myStr); //should show Y******e
You can do something like this for example:
<?php
function HideUN($username = "") {
$replaced = "";
# Count the characters in username and remove an extra asterik (*)
# Substring, remove all characters and leave the first one and add the last one
for($i = 0; $i < strlen($username) -1; $i++) $replaced .= "*";
return substr($username, 0, 1)."".$replaced."".substr($username, -1, 1);
}
# Call this function
$string = "John";
echo HideUN($string);
?>
The substr() removes all characters after the first one, then the for() loop, counts the characters from $string and then we gonna add the asterik (*) to an other variable called $replaced.
Then at the end we put them together in an echo. Output: J***n
function Split_Hide_Name($name) {
$name = trim($name);
$split_name = explode(' ',$name);
foreach($split_name as $v) {
$string []= strlen($v);
}
$number_of_letters_to_show = 3;
$first_name_length = $string[0];
$last_name_length = $string[count($string)-1];
$first_name1 = $split_name[0];
$last_name1 = $split_name[count($string)-1];
$fname_cover = '';
for ($i = 0; $i < $first_name_length - $number_of_letters_to_show; $i++){
$fname_cover .="*";
}
$lname_cover = '';
for ($i = 0; $i < $last_name_length - $number_of_letters_to_show; $i++){
$lname_cover .="*";
}
$first_name = substr_replace($first_name1,$fname_cover,$number_of_letters_to_show);
$last_name = substr_replace($last_name1,$lname_cover,$number_of_letters_to_show);
return $first_name.' '.$last_name;}

Replace quotes in a string with a HTML tag

I have the following string stored in a variable in PHP.
The words inside the quotes should be in '''bold'''. Like '''this''' and '''that'''
Here triple quotes ''' are used to represent that the word should be shown bold.
What is the most efficient way to replace this with the <strong> tag?
i would say regex with something like that :
$new_string = preg_replace('/\'\'\'([^\']+)\'\'\'/', '<strong>$1</strong>', $string);
Even though #atrepp's answer is correct, I ended up using the following function
function makeBold($string) {
$quote = ''''';
$count = substr_count($string, $quote);
for ($i = 0; $i <= $count/2; $i++) {
$string = preg_replace("/$quote/", '<strong>', $string, 1);
$string = preg_replace("/$quote/", '</strong>', $string, 1);
}
return $string;
}
because
My string was actually in encoded form (ie) it had ' instead of '
His answer doesn't work when the word to be bolded has ' in it

Create acronym from a string containing only words

I'm looking for a way that I can extract the first letter of each word from an input field and place it into a variable.
Example: if the input field is "Stack-Overflow Questions Tags Users" then the output for the variable should be something like "SOQTU"
$s = 'Stack-Overflow Questions Tags Users';
echo preg_replace('/\b(\w)|./', '$1', $s);
the same as codaddict's but shorter
For unicode support, add the u modifier to regex: preg_replace('...../u',
Something like:
$s = 'Stack-Overflow Questions Tags Users';
if(preg_match_all('/\b(\w)/',strtoupper($s),$m)) {
$v = implode('',$m[1]); // $v is now SOQTU
}
I'm using the regex \b(\w) to match the word-char immediately following the word boundary.
EDIT:
To ensure all your Acronym char are uppercase, you can use strtoupper as shown.
Just to be completely different:
$input = 'Stack-Overflow Questions Tags Users';
$acronym = implode('',array_diff_assoc(str_split(ucwords($input)),str_split(strtolower($input))));
echo $acronym;
$initialism = preg_replace('/\b(\w)\w*\W*/', '\1', $string);
If they are separated by only space and not other things. This is how you can do it:
function acronym($longname)
{
$letters=array();
$words=explode(' ', $longname);
foreach($words as $word)
{
$word = (substr($word, 0, 1));
array_push($letters, $word);
}
$shortname = strtoupper(implode($letters));
return $shortname;
}
Regular expression matching as codaddict says above, or str_word_count() with 1 as the second parameter, which returns an array of found words. See the examples in the manual. Then you can get the first letter of each word any way you like, including substr($word, 0, 1)
The str_word_count() function might do what you are looking for:
$words = str_word_count ('Stack-Overflow Questions Tags Users', 1);
$result = "";
for ($i = 0; $i < count($words); ++$i)
$result .= $words[$i][0];
function initialism($str, $as_space = array('-'))
{
$str = str_replace($as_space, ' ', trim($str));
$ret = '';
foreach (explode(' ', $str) as $word) {
$ret .= strtoupper($word[0]);
}
return $ret;
}
$phrase = 'Stack-Overflow Questions IT Tags Users Meta Example';
echo initialism($phrase);
// SOQITTUME
$s = "Stack-Overflow Questions IT Tags Users Meta Example";
$sArr = explode(' ', ucwords(strtolower($s)));
$sAcr = "";
foreach ($sArr as $key) {
$firstAlphabet = substr($key, 0,1);
$sAcr = $sAcr.$firstAlphabet ;
}
using answer from #codaddict.
i also thought in a case where you have an abbreviated word as the word to be abbreviated e.g DPR and not Development Petroleum Resources, so such word will be on D as the abbreviated version which doesn't make much sense.
function AbbrWords($str,$amt){
$pst = substr($str,0,$amt);
$length = strlen($str);
if($length > $amt){
return $pst;
}else{
return $pst;
}
}
function AbbrSent($str,$amt){
if(preg_match_all('/\b(\w)/',strtoupper($str),$m)) {
$v = implode('',$m[1]); // $v is now SOQTU
if(strlen($v) < 2){
if(strlen($str) < 5){
return $str;
}else{
return AbbrWords($str,$amt);
}
}else{
return AbbrWords($v,$amt);
}
}
}
As an alternative to #user187291's preg_replace() pattern, here is the same functionality without needing a reference in the replacement string.
It works by matching the first occurring word characters, then forgetting it with \K, then it will match zero or more word characters, then it will match zero or more non-word characters. This will consume all of the unwanted characters and only leave the first occurring word characters. This is ideal because there is no need to implode an array of matches. The u modifier ensures that accented/multibyte characters are treated as whole characters by the regex engine.
Code: (Demo)
$tests = [
'Stack-Overflow Questions Tags Users',
'Stack Overflow Close Vote Reviewers',
'Jean-Claude Vandàmme'
];
var_export(
preg_replace('/\w\K\w*\W*/u', '', $tests)
);
Output:
array (
0 => 'SOQTU',
1 => 'SOCVR',
2 => 'JCV',
)

How to remove '<' from a string?

say, i have a string like $x="History[424]<"; how to remove the last "<" and make the string $x="History[424]"; ... I tried str_replace and don't know, its not working... :(. Thx in advance
for($k=0;$k<$i;$k++) {
$linklabelmod[$k] = str_replace($linklabel[$k], $linklabel[$k]."[$k]", $linklabel[$k]);
//$var= str_replace($linklabel[$k], $linklabelmod[$k], $var);
print $linklabelmod[$k].'< ';
//print $linklabel[$k].' ';
print $link[$k].'<br>';
}
$x = rtrim($x, '<'); // no regex needed
$x = str_replace("<","",$x);
Edit: This replaces all of the "<", but as you mentioned str_replace in your question, this is how it works.
This would ensure that < is only ever removed from the end of the string, and not from anywhere else within the string;
$y = preg_replace('/<$/', '', $x );

Categories