I want to write code that finds the maximum sequence of characters at the end of an array that are the same as the beginning of the array.
But I dont know how I can do it with PHP?
For example:
Input = [a,b,c,e,r,t,x,s,b,a,b,c]
Output = [a,b,c]
(because the elements a,b,c
are both at the beginning and end of the array and they represent the maximum sequence of such characters)
Note: This will work perfectly for this kind of array, where we have array of strings, it does not work for nested array.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$data = array("a","b","c","e","r","t","x","s","b","a","b","c");
$string= implode("", $data);//converting array to string.
for($x=strlen($string)-1;$x>=0;$x--)
{
//matching substring from the end of string.
if(preg_match("/".substr($string, 0,$x)."$/",$string)==true)
{
$string= substr($string, 0,$x);
break;
}
}
$result=str_split($string);
print_r($result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With