Combining preg_match regex - php

I'm wondering if there is a way to somehow combine multiple regex statements into one? Maybe I could use an array, or can you purely do it with regex?
$reg = '/[a-zA-Z0-9]{7}$/';
$reg_l = '/[a-zA-Z0-9]{7}-lg$/';
$base = 'Fz4vqVW'; // May also be Fz4vqVW-lg
if (preg_match($reg,$base) { //Just checks for a 7 long string
echo '1';
} elseif (preg_match($reg_l,$base) { //Checks for 7 long string with -lg at the end
echo '2';
} else {
echo '0';
}

It can be combined in one regex with preg_replace_callback like this:
$reg = '/^(?:([a-zA-Z0-9]{7})(-lg)?|.*)$/';
$base = 'Fz4vqVW'; // May also be Fz4vqVW-lg
echo preg_replace_callback($reg, function($m) {
if (isset($m[2])) return 2; elseif (isset($m[1])) return 1; else return 0; }, $base);
Example Code:
$arr=array('Fz4vqVW', 'Fz4vqVW-lg', 'foobar');
foreach ($arr as $a) {
echo preg_replace_callback($reg, function($m) { if (isset($m[2])) return 2;
elseif (isset($m[1])) return 1; else return 0; }, $a)."\n";
}
Output:
1
2
0

You can also modify your preg_match() call as follows:
$reg = '/^[a-zA-Z0-9]{7}(-lg)?$/';
if (preg_match($reg, $base, $m))
echo isset($m[1]) ? 2 : 1; else echo 0;

You can simply count the number of items in the match result:
$base = 'Fz4vqVW';
$m = [];
preg_match('~^[a-zA-Z0-9]{7}(-lg)?$~D', $base, $m);
echo count($m);

Related

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';

Determine repeat characters in a php string

I have found many examples of how to find repeat characters in a string. I believe my requirement is unique.
I have string
$string=aabbbccddd;
I need to determine which character was repeated the most.
So for the above example it would say
The character repeated the most is "B".
However in the example above both B and D are repeated 3 times.
Would need to spot that. B AND D are both repeated 3 times.
This is what I have so far. FAR from what I need but starting point
<?php
$string = "aabbbccddd";
$array=array($array);
foreach (count_chars($string, 1) as $i => $val) {
$count=chr($i);
$array[]= $val.",".$count;
}
print_r($array);
?>
Anyone have any thing that could help me?
Based on georg's great point, I would use a regex. This will handle split duplicates like ddaaddd with array keys dd=>2 and ddd=>3 but will only show one entry for dd when given ddaadd. To represent both would require a more complex array:
$string = "ddaabbbccddda";
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[0], array_map('strlen', $matches[0]));
arsort($result);
If you only need a count of ALL occurrences try:
$result = array_count_values(str_split($string));
arsort($result);
Legacy Answers:
If you don't have split duplicates:
$string = 'aabbbccddd';
$letters = str_split($string);
$result = array_fill_keys($letters, 1);
$previous = '';
foreach($letters as $letter) {
if($letter == $previous) {
$result[$letter]++;
}
$previous = $letter;
}
arsort($result);
print_r($result);
Or for a regex approach:
preg_match_all('/(.)\1+/', $string, $matches);
$result = array_combine($matches[1], array_map('strlen', $matches[0]));
arsort($result);
Here's exactly what your looking for :
<?php
function printCharMostRepeated($str)
{
if (!empty($str))
{
$max = 0;
foreach (count_chars($str, 1) as $key => $val)
if ($max < $val) {
$max = $val;
$i = 0;
unset($letter);
$letter[$i++] = chr($key);
} else if ($max == $val)
$letter[$i++] = chr($key);
if (count($letter) === 1)
echo 'The character the most repeated is "'.$letter[0].'"';
else if (count($letter) > 1) {
echo 'The characters the most repeated are : ';
$count = count($letter);
foreach ($letter as $key => $value) {
echo '"'.$value.'"';
echo ($key === $count - 1) ? '.': ', ';
}
}
} else
echo 'value passed to '.__FUNCTION__.' can\'t be empty';
}
$str = 'ddaabbccccsdfefffffqqqqqqdddaaa';
printCharMostRepeated($str);
use count-chars()
http://php.net/manual/en/function.count-chars.php
and then asort()
http://php.net/manual/en/function.asort.php
<?php
$word = "abcdefghbi";
for($i=0; $i<strlen($word);$i++){
for($k=0;$k<strlen($word);$k++){
if($word[$i] == $word[$k] && $i != $k){
echo $word[$k]." is duplicate";
exit;
}
}
}
echo "no match found";
?>
$data = "aabbbcccdddz";
$array = str_split($data);
$v = array_count_values($array);
foreach($v as $k => $val){
echo $k.' = '.$val.'<br>';
}

PHP Combine two strings

Is there a way in php to make two strings combine to one? I want to combine strings with the same size together?
$string1 = "apple"
$string2 = "block"
//FUNCTION STUFF HERE
$output = "abplpolcek";
You could try this:
$output='';
for($i=0;$i<strlen($string1);$i++)
{
$output.=$string1[$i];
$output.=$string2[$i];
}
echo $output;
Or you can write a simple function like this:
function funnyConcatStrings($str1, $str2)
{
$output='';
$leng=strlen($str1);
if(strlen($str1)==strlen($str2))
{
for($i=0;$i<$leng;$i++)
{
$output.=$str1[$i];
$output.=$str2[$i];
}
}
else
{
$output='Strings were not equal.\n';
}
return $output;
}
// Use it like this:
$mashedString=funnyConcatStrings($string1, $string2);
// or
echo funnyConcatStrings($string1, $string2);
$str_length = 5;
$output = '';
for($i = 0; $i < $str_length; $i++)
{
$output .= $string1[$i] . $string2[$i];
}
use for instance $string1[0] ( letter 'a' ) to access the first letter and make a for loop
Really easy;
$a = 'abcdef';
$b = 'ghijkl';
$l = strlen($a);
$s='';
for($i=0;$i<$l;$i++)$s .= $a[$i] + $b[$i];
echo $s;
1.) Check if the string have the same lengts with strlen
2.) Then you can iterate through the string and access them as an array
$string = 'test123';
echo $string[0] -> 't'
Then you can combine the string and safe them in a new variable.
This will work for strings that are different lenght as well
$string1 = "apple";
$string2 = "block";
$arr1 = str_split($string1);
$arr2 = str_split($string2);
if(count($arr1) > 0)
{
foreach($arr1 as $key => $value)
{
$_tmp[] = $value;
if(isset($arr2[$key]))
{
$_tmp[] = $arr2[$key];
}
}
}
else
{
$key = 0;
}
if($key + 1 < count($arr2))
{
for($i = $key + 1; $i < count($arr2); $i++)
{
$_tmp[] = $arr2[$key];
}
}
echo implode("", $_tmp);
echo str_shuffle("apple" . "block");
result: aekbplopcl

How to get the count of string 2 occurrence in string 1 without php built-in functions

How to get the count of string 2 occurrence in string 1 without php built-in functions.
Example:
$strone = "Arun sukumar";
$strtwo = "a";
//Expected Output: 2
$strone = "Arun sukumar";
$strtwo = "uk";
//Expected Output: 1
I need to get the count without using any php built-in functions.
This is the question asked in a interview, is there any logic in that?
You need to take your needle, get the first char.. then iterate over each char of the haystack until you get match. Then take the next char of needle and check the next char of the haystack for a match... continue until you have the complete match for needle or until you fial to match a char.
hint: you can access the individual chars of a string by index with $string{0} where 0 is the zero based index of the char in the string.
$strone = 'arun sukumar';
$strtwo = 'a';
echo parsestr($strone, $strtwo);
function parsestr($strone, $strtwo)
{
$len = 0;
while ($strtwo{$len} != '') {
$len++;
}
$nr = 0;
while ($strone{$nr} != '')
{
if($strone{$nr} != ' ')
{
$data[$nr] = $strone{$nr};
}
$nr++;
}
$newdata = $data;
if($len > 1)
{
$newdata = array();
$j = 0;
foreach($data as $val)
{
$str .= $val;
if($j == ($len -1))
{
$newdata[] = $str;
$str = '';
$j = 0;
}
else
$j++;
}
}
$i = 0;
foreach($newdata as $val)
{
if($val == $strtwo)
{
$i++;
}
}
return $i;
}
Try this
$string = 'Arun sukumar';
$sub_string = 'a';
$count = 0;
for($i=0;$i < strlen($string); $i++){
$flag = 0;
$j=0;
if(strtolower($string[$i]) == $sub_string[$j])
{
//echo "match";
$flag = 1;
$k = $i;
for(;$j< strlen($sub_string); $j++){//echo "[".$j . $k."] $count $flag";
if(strtolower($string[$k]) != $sub_string[$j]){
$flag = 0;
break;
}
$k++;
}//echo "<br> $flag";
}
if($flag == 1){
$count++;
$flag = 0;
}
}
echo $count;
?>
Not sure why you would not want to use the built-in PHP functions since they would be faster, but something like this would work:
<?php
$haystack = 'Arun sukumar';
$needle = 'a';
// you seem to want a case insensitive search, so do a strtolower first
$haystack = strtolower($haystack);
$hitCount = 0;
for ($i = 0; $i < strlen($haystack); ++$i) {
if ($needle === substr($haystack, $i, strlen($needle))) {
$hitCount++;
}
}
echo 'Output: ' . $hitCount;
?>

How to find string length in php with out using strlen()?

How can you find the length of a string in php with out using strlen() ?
I know this is a pretty old issue, but this piece of code worked for me.
$s = 'string';
$i=0;
while ($s[$i] != '') {
$i++;
}
print $i;
$inputstring="abcd";
$tmp = ''; $i = 0;
while (isset($inputstring[$i])){
$tmp .= $inputstring[$i];
$i++;
}
echo $i; //final string count
echo $tmp; // Read string
while - Iterate the string character 1 by 1
$i - gives the final count of string.
isset($inputstring[$i]) - check character exist(null) or not.
I guess there's the mb_strlen() function.
It's not strlen(), but it does the same job (with the added bonus of working with extended character sets).
If you really want to keep away from anything even related to strlen(), I guess you could do something like this:
$length = count(str_split($string));
I'm sure there's plenty of other ways to do it too. The real question is.... uh, why?
Lets be silly
function stupidCheck($string)
{
$count = 0;
for($i=0; $i<66000; $i++)
{
if(#$string[$i] != "")$count++;
else break;
}
return $count;
}
Simply you can use the below code.
<?php
$string="Vasim";
$i=0;
while(isset($string[$i]))
{
$i++;
}
echo $i; // Here $i has length of string and the answer will be for this string is 5.
?>
The answer given by Vaibhav Jain will throw the following notice on the last index.
Notice: Uninitialized string offset
I would like to give an alternative for this:
<?php
$str = 'India';
$i = 0;
while(#$str[$i]) {
$i++;
}
echo 'Length of ' . $str . ' is ' . $i . '.';
mb_strlen — Get string length
$string ='test strlen check';
print 'mb_strlen(): ' . mb_strlen( $string, 'utf8' ) . "\n\n";
synatx: int mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] )
str - The string being checked for length.
encoding - The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.
In newer PHP versions, you can use null coalescing operator to achieve this.
<?php
$string = 'test';
for($i = 0; ($string[ $i] ?? false) !== false; ++$i);
echo $i;// outputs length of the string.
Online Demo
You could also cheat with something like:
print strtok(substr(serialize($string), 2), ":");
Or this one is quite amusing:
print array_sum(count_chars($string));
function mystrlen($str)
{
$i = 0;
while ($str != '')
{
$str = substr($str, 1);
$i++;
}
return $i;
}
function findStringLength($string) {
$length = 0;
$lastStringChar1 = '1';
$lastStringChar2 = '2';
$string1 = $string . $lastStringChar1;
$string2 = $string . $lastStringChar2;
while ($string1[$length] != $lastStringChar1 || $string2[$length] != $lastStringChar2) {
$length++;
}
return $length;
}
You can use this code for finding string length without using strlen() function.
<?php
function stringlength($withoutstringlength)
{
$n = 0;
while(substr($withoutstringlength, $n, $n+1) != '')//General syntax substr(string,start,length)
{
$n++;
}
echo $n;
}
stringlength("i am a php dev");
?>
Try this:
function length($value){
if(empty($value[1])) return 1;
$n = 0;
while(!empty($value[$n+1])){
$n++;
}
return $n+1;
}
This doesn't use loops but may face the O(n) issue if strrpos uses strlen internally.
function length($str)
{
return strrpos($str.'_', '_', -1);
}
function my_strlen($str)
{
for($i=-1; isset($str[++$i]); );
return $i;
}
echo my_strlen("q");
$str = "Hello World";
$count= 0;
while( isset($str[$count]) && $str[$count] ) {
$count++;
}
echo $count;
OUTPUT:
11
Renverser un charactère sans Function
class StringFunction {
public function strCount($string) {
$cpt=0;
//isset pour cacher l'erreur
// Notice: Uninitialized string offset
while(isset($string[$cpt])) {
$cpt++;
}
return $cpt;
}
public function reverseChar($str) {
//mes indexes
$start = 0;
$end = $this->strCount($str)-1;
//Si $start est inférieur à $end
while ($start < $end) {
//change position du charactère
$temp = $str[$start];
$str[$start] = $str[$end];
$str[$end] = $temp;
$start++;
$end--;
}
return $str;
}
}
$string = "Bonjour";
$a = new StringFunction();
echo $string . "<br>";
echo $a->reverseChar($string);
This code will help you when you don't want to use any inbuilt function of php.
You can test this here also
http://phptester.net/
<?php
$stings="Hello how are you?";
$ctr=0;
while(1){
if(empty($stings[$ctr])){
break;
}
$ctr++;
}
echo $ctr;
<?php
$str = "aabccdab";
$i = 0;
$temp = array();
while(isset($str[$i])){
echo $str[$i];
$count = 0;
if(isset($temp[$str[$i]])){
$temp[$str[$i]] = $temp[$str[$i]]+1;
}else{
$temp[$str[$i]] = 1;
}
$i++;
}
print_r($temp);
?>
It's going to be a heavy work for your server, but a way to handle it.
function($string){
$c=0;
while(true){
if(!empty($string[$c])){
$c=$c+1;
} else {
break; // Prevent errors with return.
}
}
return $c;
}
$str = "STRING";
$i=0; $count = 0;
while((isset($str{$i}) && $str{$i} != "")){
$i++; $count++;
}
print $count;
This can also help -
$s = 'string';
$temp = str_split($s); // Convert a string to an array by each character
// if don't want the spaces
$temp = array_filter($temp); // remove empty values
echo count($temp); // count the number of element in array
Output
6
<?php
$arr = array('vadapalanai','annanager','chennei','salem','coimbatore');
$min = $arr[0];
$max = $arr[0];
foreach($arr as $key => $val){
if (strlen($min) > strlen($val)) {
$min = $val ;
}
if(strlen($max) < strlen($val)){
$max = $val;
}
}
echo "The shortest array length is : " .$min. " ".strlen($min);
echo "<br>";
echo "The longest array length is: " .$max. " ".strlen($max);
?>
$str = 'I am XYZ'
$count = 0;
$i=0;
while (isset($str[$i])) {
$count = $i;
$i++;
}
echo $count;

Categories