Remove words starting with uppercase - php

I have a string, for example FastFood, how do I remove Food and leave only first word? Also it could be VeryFastFood, then Very should be left, etc.
Some strings may containt 3 uppercase starting letters. I need then only this 3 letters to be left. for example YOUProblem - must be YOU.

Here is a function that can do it for you as well:
function removeUppercase($word){
if(ctype_upper(substr($word,0,3))) //Check for first 3 uppercase and return those
return substr($word,0,3);
for($a=1;$a<strlen($word);$a++){ //Otherwise loop through letters until uppercase is found
if(ctype_upper($word[$a]))
return substr($word,0,$a);
}
return $word;
}

Here is a hackish solution, first thing I could think of
<?php
$string = "VeryFastFood";
$found = false;
$tmp = '';
for($i = 0; $i < strlen($string); ++$i)
{
$char = $string[$i];
if(ctype_upper($char))
{
if($found)
{
break;
}
else
{
$found = true;
}
}
$tmp .= $char;
}
$string = $tmp;
var_dump($string);

preg_match(/^[A-Z]([A-Z]{2}|[A-Z][a-zA-Z]|[a-z]{2})[a-z]*/), $stringToCheck, $matches);
$matches[0] //has your string
Something like this should work.

Related

Three the same characters in a row in string PHP

I have no idea how to create function which counts how many times 3 the same letters in a row reapets in one string?
For example: avcdddjrg return 1, aaargthbbb return 2
I can detect if there are 3 the same characters in a row, but can't figure it out how to count it
$input = 'hellooommm';
if (preg_match('/(.)\1{2}/', $input)) {
return 1;
}else {
return 0;
}
Thank you
Use preg_match_all(), like this:
$input = 'hellooommm';
$n = preg_match_all('/(.)\1{2}/', $input);
if ($n !== false) {
echo "$n matches found", PHP_EOL;
} else {
echo "an error occurred when calling preg_match_all()", PHP_EOL;
}
#hek2mgl's answer above is simple and eloquently solves the problem using regex. But I get the feeling you may benefit from hashing this out logically a bit more. Another approach you could use is iterating over the characters and counting the repetitions like this:
function countGroupsOfThree($str) {
$length = strlen($str);
$count = 1;
$groups = 0;
for ($i = 0; $i < $length; $i++){
// is this character the same as the last one?
if ($i && $str[$i] === $str[$i-1]) {
// if so, increment the counter
$count++;
// is this the third repeated character in a row?
if ($count == 3) {
// if so, increment $groups
$groups++;
}
} else {
// if not, reset the counter
$count = 1;
}
}
return $groups;
}
$str = 'aaavgfwbbb3ds';
echo countGroupsOfThree($str);
OUTPUT: 2
In the grand scheme of things, this function is probably not very useful but hopefully it illustrates some key concepts that will help you figure things like this out in the future.

Php Program to find Palindrome?

Three steps to find the palindrome?
use strrev on the given value
Then split using the str_split.
Then use foreach and concate the split value.
Example
$a = "madam";
$b = strrev($a);
$string_reverse = str_split($b);
$palin = '';
foreach($string_reverse as $value){
$palin.= $value;
}
print $palin;
if($a == $palin){
print "<br>Palindrome";
} else {
print "<br>Not Palindrome";
}
Output
madam
Palindrome
try this:
<?php
function check_plaindrome($string) {
//remove all spaces
$string = str_replace(' ', '', $string);
//remove special characters
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
//change case to lower
$string = strtolower($string);
//reverse the string
$reverse = strrev($string);
if ($string == $reverse) {
echo "<p>It is Palindrome</p>";
}
else {
echo "</p>Not Palindrome</p>";
}
}
$string = "A man, a plan, a canal, Panama";
check_plaindrome($string);
########Output#######
<p>It is Palindrome</p>
To check a string whether it is palindrome or not without PHP function.
<?php
$str = 'level';
$strLen = strlen($str)-1;
$revStr = '';
for($i=$strLen; $i>=0; $i--){
$revStr.=$str[$i];
}
if($revStr == $str)
echo 'Palindrome';
else
echo "Not Palindrome";
?>
function checkpala(string $input){
for( $i=0; $i < strlen($input); $i++){ //for each char in the string
if (substr($input,$i,1) != substr($input, strlen($input)-($i+1),1)){ //get the first char and the last char and compare them. Then get the 2nd and the 2nd from the end and compare them. repeate
//if at any point there is no match, stop checking, return false
//echo "$input is not a palindrome";
return false;
}
}
//if the loop completes and every character checked out, return true.
//echo "$input is a palindrome";
return true;
}
There is a simple way who we can write like this to don't make it complicate:
$a = "1681";
$b = strrev($a);
print $b;
if($a == $b){
print "<br>Plaindrome";
} else {
print "<br>Not Plaindrome";
}
You can try this, it reverses the string or value...
function fn_palindrome($palindrome) {
$reversed = '';
$original = $palindrome;
$string = array(); $j = 0;
$converted = (string) $palindrome;
$palindrome = str_split($converted);
$i = count($palindrome) - 1;
while($i >= 0) {
$string[$j] = $palindrome[$i];
$j++; $i--;
}
$reversed = implode('', $string);
if($reversed == $original) {
return TRUE;
} else {
return FALSE;
}
}
function checkPalindrome($string) {
return $string == strrev($string);
}
<?php
$word = "level"; // declare a varibale
echo "String: " . $word . "<br>";
$reverse = strrev($word); // reverse the word
if ($word == $reverse) // compare if the original word is same as the reverse of the same word
echo 'Output: This string is a palindrome';
else
echo 'Output: This is not a palindrome';
?>
Dummy String to be tested
$s = 'abcdefg';
Reverse the string order
$t = strrev($s);
Get the length of the string
$length = mb_strlen($s);
Variable to be used for concating string while traversing using for loop
$new = '';
Loop to traverse string
for ($i = 0; $i < $length; $i++) {
$new = $s[$i].$new;
}
Check string traversed using for loop is equal to string reversed using PHP function
if ($s == $new){
echo "Yes palindrome";
} else {
echo "No palindrome";
}
If output is yes then it is palindrome otherwise it is Not a palindrome string.
*** I have update the answer.
You can try the following code:
function checkPalindrome($string){
$string = strtolower($string);
$reverse = strrev($string);
if($string == $reverse){
return true;
} else {
return false;
}
}
Try this one..
<?php
$strng = 'SMS';
$rvsstr = '';
$i = 0;
while (!empty($strng[$i])) {
$rvsstr = $strng[$i].$rvsstr;
$i++;
}
// echo $rvsstr;
if ($strng === $rvsstr) {
echo "Number is Palindrome";
} else {
echo "Number is not palindrome";
}
?>
Could it be as simple as this?
function isPalindrome(string $word) : bool
{
$word = strtolower($word);
if(strrev($word) === $word){
return true;
} else {
return false;
}
}
echo isPalindrome('Deleveled');
People are already correct here, anyway simply you can try this.
function checkPalindrome($string) {
$string = strtolower($string);
return $string == strrev($string);
}
function isPalindrome($string): bool {
return strtolower($string) === strtolower(strrev($string));
}
Didn't find solution for my 'kąyąk' problem when You have different characters encoding.
Below is originally from php.net comment changed sligtly by me to see on xdebug in phpStorm whats going on.
public function isPalindrome(): bool {
$r = '';
for ($i = mb_strlen($this->string); $i >= 0; $i--) {
$r .= mb_substr($this->string, $i, 1);
}
for ($i = 0 ; $i <= strlen($r); $i++) {
$o = mb_substr($this->string, $i, 1); // original current char
$s = mb_substr($r, $i, 1); // inverted current char
if ($o != $s) {
return false; // if does not match return false
}
}
return true;
}
$a = readline("Enter word: ");
$i=0;
for ($i=0; $i < strlen($a) && substr($a,$i,1) == substr($a,strlen($a)-($i+1),1); $i++);
echo ($i == strlen($a))?"Pallindrome":"Not Pallindrome";
$i < strlen($a) && substr($a,$i,1) == substr($a,strlen($a)-($i+1),1)
This test is the key where the loop tries to keep checking if the characters starting from the left of the string matches with the characters from the right, and it should continue till all characters are checked or till it doesn't find a matching character.
So, first of all, what is palindrome?
Palindrome is a word, phrase, or sequence that reads the same backward as forward.
So, to know wether the string is a palindrome or not, we only need to reverse the original string and then compare it.
Let's say we want to check wether the string Level is a palindrome or not:
$str = 'Level';
This step is for ignoring the case-sensitivity so Level and level will be considered the same.
$str = strtolower($str);
Then we can use the strrev() to reverse the string, then compare it to the original as follow:
echo (strrev($str) === $str) ? 'Palindrome' : 'Not palindrome';
You can also write it with if-else block if you consider it easier to read:
if (strrev($str) === $str) {
echo "Palindrome";
} else {
echo "Not palindrome";
}
Final code:
$str = 'Level';
$str = strtolower($str);
echo (strrev($str) === $str) ? 'Palindrome' : 'Not palindrome';

delete the repetetion letters in a string php

I'm trying to parse a string and delete the adjacent letters that are same. I want to return the count of number of deletions and output the resulted string after the deletions are made. Say I have
$str = "aaabbbcc";
As you can see, you need to do 5 deletions to make the adjacent letters not same. The $output string is "abc" and the number of deletions is five.
function str_deletions ($str)
{
$prev = $str[0];
$length = strlen($str);
$deletions = 0;
$output = "";
for ($i=1 ; $i < $length; $i++)
{
if ($str[$i]== $prev)
{
$deletions++;
$prev = $str[$i]; // not sure here ?
}
}
echo $output; // ?
return $deletions;
}
$str = "aabbcc";
echo str_deletions ($str);
EDIT
This is an interview question, I'm not supposed to use any built-in functions like regex or array_count_values
Thanks for your help !
Here is another regex solution. I use a regex to only match a word character that is repeated, and then remove each consecutive repeating character one by one, which allows me to use &$count argument with preg_replace:
count
If specified, this variable will be filled with the number of replacements done.
The regex is
(\w)(?=\1)
See demo. Note you can replace \w with . to match any character but a newline. OR if you need to match only letters, I suggest using '/(\p{L})(?=\1)/u'
See IDEONE demo:
$str = "aaabbbcc";
$cnt = -1;
$result = preg_replace('/(\w)(?=\1)/', "", $str, -1, $cnt);
echo "Result: " . $result . PHP_EOL . "Deletions: " . $cnt;
Output:
Result: abc
Deletions: 5
Regex solution
This is a much simpler way of doing what you're after using preg_replace():
<?php
function str_deletions($str){
$replaced = preg_replace("/(.)\\1+/", "", $str);
$length = strlen($str) - strlen($replaced);
return array("new_word" => $replaced, "chars_replaced" => $length);
}
$str = "aabbcc";
$string_deletions = str_deletions($str);
echo "New String: " . $string_deletions['new_word'] . "\n";
echo "Chars deleted: " . $string_deletions['chars_replaced'] . "\n";
?>
No inbuilt functions
For the purposes of completion (and since you updated your question with more information to say that we can't use regexes because it's an interview question), here's what I'd do:
Using count_chars():
function str_deletions($str){
$string_data['new_word'] = count_chars($str,3);
$string_data['chars_replaced'] = strlen($str) - strlen($string_data['new_word']);
return $string_data;
}
$str = "aabbcc";
echo str_deletions($str);
Note: in this example count_chars(); will return unique chars in a string, not quite remove duplicates (i.e. "aabbccaa" would still yield "abc" as an output) but your question wasn't clear what the interviewer wanted - whether it was truly a remove duplicate question or a unique char question.
Using array_unique():
Slightly slower and a bit more heavy handed:
function str_deletions($str){
$string_array = array_unique(str_split($str));
foreach($string_array as $string_cur){
$string_data['new_word'] .= $string_cur;
}
$string_data['chars_replaced'] = strlen($str) - strlen($string_data['new_word']);
return $string_data;
}
$str = "aabbcc";
echo str_deletions($str);
Note: It's worth pointing out that if I realised it was an interview question, I wouldn't have provided an answer as doing it for you kind of defeats the purpose. Still, with the amount of answers here now and the fact that I've seen something similar to this in an interview, my hope is someone will learn from these.
The basic algorithm (indeed $prev = $str[$i]; isn't at the good place but you wasn't far):
function str_deletion($str) {
$del = 0;
if (1 < $length = strlen($str)) { // $str has more than 1 char
$prev = $str[0];
$output = $prev;
for ($i=1; $i<$length; $i++) {
if ($prev == $str[$i]) {
$del++;
} else {
$prev = $str[$i]; // when different, change the previous character
$output .= $prev; // and append it to the output
}
}
} else {
$output = $str;
}
echo $output;
return $del;
}
I have changed your function
this is not returning both the output string and number of deletions
function str_deletions ($str)
{
$prev = NULL;
$deletions = 0;
$output = "";
$i=0;
while ($i < strlen($str))
{
if (substr($str,$i,1) == $prev)
{
$deletions++;
//$prev = substr($str,$i,1);/*remove this line, no need here as the same stmnt is there after ifelse*/
}else{
$output.=substr($str,$i,1);
}
$prev = substr($str,$i,1);
$i++;
}
$arr = array(
'output'=>$output,
'deletions'=>$deletions
);
return $arr;
}
$str = "aaabbcc";
print_r(str_deletions ($str));
output for above function call is
Array ( [output] => abc [deletions] => 4 )
Solved with no external function except count;
$str="aaavvvffccca";
$count = strlen($str);
for($i=0;$i<$count;$i++){
$array[]=$str[$i];
}
$del =0;
for($i=0;$i<$count;$i++){
$next=isset($array[$i+1])?$array[$i+1]:null;
if($array[$i]==$next)
{
$del++;
}
else
{
$newarray[]=$array[$i];
}
}
echo "Filter Text:". implode('',$newarray);
echo"Total Deleted:".$del;
The straight forward solution to find out the number of deletions can be
If there are N consecutive same characters delete N-1 out of those N characters.
function str_likes($str)
{
$length = strlen($str);
$del = 0;
for ($i=0 ; $i < $length ; $i++)
{
if ($str[$i] == $str[$i+1])
{
$del++;
}
}
return $del;
}
$str = "aabbccaaa";
echo str_likes($str); //4

Determine the position of a special character in the string in PHP

I have to determine the position of a special character in the string for example:
E77eF/74/VA on 6 and 9 position (counting from 1)
we have '/' so I have to change them to position number -> E77eF6749VA
On MSSQL I could use PATINDEX but I need to use php for this.
It should work for everything except 0-9a-zA-Z
I found strpos() and strrpos() on php.net but I doens't work well for me.
Anyway tries to do something like that?
<?php
$content = 'E77eF/74/VA';
//With this pattern you found everything except 0-9a-zA-Z
$pattern = "/[_a-z0-9-]/i";
$new_content = '';
for($i = 0; $i < strlen($content); $i++) {
//if you found the 'special character' then replace with the position
if(!preg_match($pattern, $content[$i])) {
$new_content .= $i + 1;
} else {
//if there is no 'special character' then use the character
$new_content .= $content[$i];
}
}
print_r($new_content);
?>
Output:
E77eF6749VA
Might not be the most efficient way, but works.
$string = 'E77eF/74/VA';
$array = str_split($string);
foreach($array as $key => $letter){
if($letter == '/'){
$new_string.= $key+1;
}
else{
$new_string.= $letter;
}
}
echo $new_string; // prints E77eF6749VA

How to get position of last letter in a string in php?

Example of a string: "Some text.....!!!!!!!!?????"
Using PHP how would I get the position of the last letter (or even alphanum character) which in this example is the letter t?
You could use preg_match_all with the regular expression \p{L} to find all Unicode letters. With the additional flag PREG_OFFSET_CAPTURE you get also the offsets:
$str = "Some text.....!!!!!!!!?????";
if (preg_match_all('/\p{L}/u', $str, $matches, PREG_OFFSET_CAPTURE) > 0) {
$lastMatch = $matches[0][count($matches[0])-1];
echo 'last letter: '.$lastMatch[0].' at '.$lastMatch[1];
} else {
echo 'no letters found';
}
$s = "Some text.....!!!!!!!!embedded?????";
$words = str_word_count($s,2);
$lastLetterPos = array_pop(array_keys($words)) + strlen(array_pop($words)) - 1;
echo $lastLetterPos;
If you want to allow for alphanum rather than just alpha:
$s = "Some text.....!!!!!!!!embedded21?????";
$words = str_word_count($s,2,'0123456789');
$lastLetterPos = array_pop(array_keys($words)) + strlen(array_pop($words)) - 1;
echo $lastLetterPos;
To add other characters as valid:
$s = "Some text.....!!!!!!!!embedded!!à?????";
$words = str_word_count($s,2,'0123456789ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöùúûüýÿ');
$lastLetterPos = array_pop(array_keys($words)) + strlen(array_pop($words)) - 1;
echo $lastLetterPos;
try substr() ;)
echo substr('abcdef', -1, 1);
It all depends on what you consider a letter, and what you want to do with "Some!!!???text???!!!" for example:
The naive solution would be to iterate from the last position in the string to find the first character you want to keep, then return that. (Or iterate from the beginning to find the first character you want to stop at, then return the one before it.)
Or you can use a regex to match what you want to keep, then take the last match. (Or use a regex replace to remove what you don't want to keep, then take the last character.)
Naive:
<?php
$s = "Some text.....!!!!!!!!?????";
$ary = str_split($s);
$position = 0;
$last = 0;
foreach ($ary as $char) {
if (preg_match("/[a-zA-Z0-9]/", $char)) {
$last = $position;
}
$position += 1;
}
echo $last;
?>
<?php
$str = '"Some text.....!!!!!!!!?????"';
$last = -1;
foreach(range('a', 'z') as $letter)
{
$last = max($last, strripos($str, $letter));
}
echo "$last\n"; // 9
?>
Here is a simple and straight-forward O(n) algorithm.
From the manual for ctype_alpha():
In the standard C locale letters are
just [A-Za-z]
If you need a different locale, you should abstract the function that determines if a character is alpha or not. That way you can keep this algorithm and adapt to varying languages.
function lastAlphaPosition($string) {
$lastIndex = strlen($string)-1;
for ($i = $lastIndex; $i > 0; --$i) {
if (ctype_alpha($string[$i])) {
return $i;
}
}
return -1;
}
$testString = 'Some text.....!!!!!!!!?????';
$lastAlphaPos = lastAlphaPosition($testString);
if ($lastAlphaPos !== -1) {
echo $testString[$lastAlphaPos];
} else {
echo 'No alpha characters found.';
}

Categories