How to splitting words match by patterns with PHP - php

I have an array of words. e.g.,
$pattern = ['in', 'do', 'mie', 'indo'];
I wanna split a words match by the patterns to some ways.
input =
indomie
to output =
$ in, do, mie
$ indo, mie
any suggests?
*ps sorry for bad english. thank you very much!

it was an very interesting question.
Input:-
$inputSting = "indomie";
$pattern = ['in', 'do', 'mie', 'indo','dom','ie','indomi','e'];
Output:-
in,do,mie
in,dom,ie
indo,mie
indomi,e
Approach to this challenge
Get the pattern string length
Get the all the possible combination of matrix
Check whether the pattern matching.
if i understand your question correctly then above #V. Prince answer will work only for finding max two pattern.
function sampling($chars, $size, $combinations = array()) {
if (empty($combinations)) {
$combinations = $chars;
}
if ($size == 1) {
return $combinations;
}
$new_combinations = array();
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination . $char;
}
}
return sampling($chars, $size - 1, $new_combinations);
}
function splitbyPattern($inputSting, $pattern)
{
$patternLength= array();
// Get the each pattern string Length
foreach ($pattern as $length) {
if (!in_array(strlen($length), $patternLength))
{
array_push($patternLength,strlen($length));
}
}
// Get all the matrix combination of pattern string length to check the probablbe match
$combination = sampling($patternLength, count($patternLength));
$MatchOutput=Array();
foreach ($combination as $comp) {
$intlen=0;
$MatchNotfound = true;
$value="";
// Loop Through the each probable combination
foreach (str_split($comp,1) as $length) {
if($intlen<=strlen($inputSting))
{
// Check whether the pattern existing
if(in_array(substr($inputSting,$intlen,$length),$pattern))
{
$value = $value.substr($inputSting,$intlen,$length).',';
}
else
{
$MatchNotfound = false;
break;
}
}
else
{
break;
}
$intlen = $intlen+$length;
}
if($MatchNotfound)
{
array_push($MatchOutput,substr($value,0,strlen($value)-1));
}
}
return array_unique($MatchOutput);
}
$inputSting = "indomie";
$pattern = ['in', 'do', 'mie', 'indo','dom','ie','indomi','e'];
$output = splitbyPattern($inputSting,$pattern);
foreach($output as $out)
{
echo $out."<br>";
}
?>

try this one..
and if this solves your concern. try to understand it.
Goodluck.
<?php
function splitString( $pattern, $string ){
$finalResult = $semiResult = $output = array();
$cnt = 0;
# first loop of patterns
foreach( $pattern as $key => $value ){
$cnt++;
if( strpos( $string, $value ) !== false ){
if( implode("",$output) != $string ){
$output[] = $value;
if( $cnt == count($pattern) ) $semiResult[] = implode( ",", $output );
}else{
$semiResult[] = implode( ",", $output );
$output = array();
$output[] = $value;
if( implode("",$output) != $string ){
$semiResult[] = implode( ",", $output );
}
}
}
}
# second loop of patterns
foreach( $semiResult as $key => $value ){
$stackString = explode(",", $value);
/* if value is not yet equal to given string loop the pattern again */
if( str_replace(",", "", $value) != $string ){
foreach( $pattern as $key => $value ){
if( !strpos(' '.implode("", $stackString), $value) ){
$stackString[] = $value;
}
}
if( implode("", $stackString) == $string ) $finalResult[] = implode(",", $stackString); # if result equal to given string
}else{
$finalResult[] = $value; # if value is already equal to given string
}
}
return $finalResult;
}
$pattern = array('in','do','mie','indo','mi','e', 'i');
$string = 'indomie';
var_dump( '<pre>',splitString( $pattern, $string ) );
?>

Related

Check if a word can be created from a random letter string using PHP

<?php
$randomstring = 'raabccdegep';
$arraylist = array("car", "egg", "total");
?>
Above $randomstring is a string which contain some alphabet letters.
And I Have an Array called $arraylist which Contain 3 Words Such as 'car' , 'egg' , 'total'.
Now I need to check the string Using the words in array and print if the word can be created using the string.
For Example I need an Output Like.
car is possible.
egg is not possible.
total is not possible.
Also Please Check the repetition of letter. ie, beep is also possible. Because the string contains two e. But egg is not possible because there is only one g.
function find_in( $haystack, $item ) {
$match = '';
foreach( str_split( $item ) as $char ) {
if ( strpos( $haystack, $char ) !== false ) {
$haystack = substr_replace( $haystack, '', strpos( $haystack, $char ), 1 );
$match .= $char;
}
}
return $match === $item;
}
$randomstring = 'raabccdegep';
$arraylist = array( "beep", "car", "egg", "total");
foreach ( $arraylist as $item ) {
echo find_in( $randomstring, $item ) ? " $item found in $randomstring." : " $item not found in $randomstring.";
}
This should do the trick:
<?php
$randomstring = 'raabccdegep';
$arraylist = array("car", "egg", "total");
foreach($arraylist as $word){
$checkstring = $randomstring;
$beMade = true;
for( $i = 0; $i < strlen($word); $i++ ) {
$char = substr( $word, $i, 1 );
$pos = strpos($checkstring, $char);
if($pos === false){
$beMade = false;
} else {
substr_replace($checkstring, '', $i, 1);
}
}
if ($beMade){
echo $word . " is possible \n";
} else {
echo $word . " is not possible \n";
}
}
?>

PHP inside foreach issue

I have this foreach :
<?php foreach ($manufacturers as $key => $manufacturer) {
if($manufacturer->virtuemart_manufacturercategories_id == 1){
$lang = 'heb'; //Hebrew
} else {
$lang = 'eng'; //English
}
//add to letter list
$letter = mb_substr($manufacturer->mf_name, 0, 1, 'UTF-8');
${'html_letters_'.$lang}[] = $letter;
/*
echo '<pre>';
print_r($manufacturer);
echo '</pre>';*/
$link = JROUTE::_('index.php?option=com_virtuemart&view=category&virtuemart_manufacturer_id=' . $manufacturer->virtuemart_manufacturer_id);
${'html_manufacturers_'.$lang} .= '<div class="manufacturer" data-lang="'.$lang.'" data-letter="'.$letter.'"><a href="'.$link.'">';
?>
<?php
if ($manufacturer->images && ($show == 'image' or $show == 'all' )) {
${'html_manufacturers_'.$lang} .= $manufacturer->images[0]->displayMediaThumb('',false);
}
if ($show == 'text' or $show == 'all' ) {
${'html_manufacturers_'.$lang} .= '<div>'.$manufacturer->mf_name.'</div>';
}
${'html_manufacturers_'.$lang} .= '</a>
</div> <!-- /manufacturer -->';
if ($col == $manufacturers_per_row){
$col = 1;
} else {
$col++;
}
}
?>
How i check if i have more then 2 same letters and unset all others but keep one.
The output for letter is :
AABCHKIUKP
I want this will be :
ABCHKIUKP
How i do this ?
EDIT: I have updated all the foreach code. The issue is if i have more then same start letter in name EG:Aroma,Air the loop the take the first letter A and foreach him 2 times, i want to show only one if there even 10 same start letter in name .
Thanks.
When I understand you right ... just use an array
<?php
$letters = array();
foreach ($manufacturers as $key => $manufacturer) {
....
$letter = mb_substr($manufacturer->mf_name, 0, 1, 'UTF-8');
$letters[] = $letter;
}
$uni = array_unique($letters)
echo implode('',$uni);
$s = 'AABCHKIUKP';
$letters = $letters = preg_split('/(?<!^)(?!$)/u', $s); //utf8
$prev_letter = '';
$temp = '';
foreach($letters as $key => $letter) {
if (!($letter === $prev_letter)) {
$temp .= $letter;
}
$prev_letter = $letter;
}
echo $temp;
Result:
ABCHKIUKP
Info about breaking a utf8 string to an array you can find at comments here mb_split.
To strip ONLY same consecutive chars you can use this:
function stripConsecutiveChars( $string ) {
// creates an array with chars from the string
$charArray = str_split( $string );
// saves the last char thats on the new string
$lastChar = "";
// variable for the new string to return
$returnString = "";
foreach( $charArray as $char ) {
if( $char === $lastChar ) continue;
$lastChar = $char;// save current char
$returnString .= $char;// concat current char to new string
}
return $returnString;
}
$string = "AABCHKIUKP";
echo stripConsecutiveChars( $string );
In your example you could try this:
...
$letter = mb_substr( $manufacturer->mf_name, 0, 1, 'UTF-8' );
$lastLetter = end( ${'html_letters_' . $lang} );//point to last element in array
reset( ${'html_letters_' . $lang} );// reset the pointer
if( $letter === $lastLetter ) {
// i guess you just want to continue?
continue;
}
...
OUTPUT:
ABCHKIUKP

Position of an element in an array with Starting Character of the element

I Wan to find a positions of an element using the starting character of the element. the example as follow
array(
0=>"1-2",
1=>"2-3"
2=>"3-4"
3=>"4-3"
)
This is my array. in This array i want find the positions of element starting with 2-, How can i find with PHP, can any one help.
Just try with:
$input = array(
0 => "1-2",
1 => "2-3",
2 => "3-4",
3 => "4-3",
);
$search = '2-';
$index = -1;
foreach ($input as $key => $value) {
if (strpos($value, $search) === 0) {
$index = $key;
break;
}
}
This would be my approach if you want to find a string starting with particular characters:
<?php
$find = '2-';
$array = array(0=>"1-2", 1=>"2-3", 2=>"3-4", 3=>"4-3");
$position = NULL;
foreach($array as $key=>$val){
if( substr($val,0,strlen($find)) == $find ){
$position = $key;
break;
}
}
echo $position;
I used strlen in the substr() to allow for any string of characters.
$input = array('1-2', '2-3', '3-4', '4-3');
$search = '2-';
var_dump(preg_grep("/^{$search}/", $input));
$needle = '2-';
$result = array_filter(
$myArray,
function($value) use ($needle) {
return fnmatch($needle.'*', $value);
}
);
var_dump($result);
A more general approach is:
$input = array('1-2', '2-3', '3-4', '4-3');
$search = '2-';
$results = array_filter(
$input,
function ($item) use ($search) {
return strpos($item, $search) === 0;
}
);
// $results will contain an array of all strings that match.

Multiple String Replace Based on Index

I need to replace multiple sections of a string based on their indices.
$string = '01234567890123456789';
$replacements = array(
array(3, 2, 'test'),
array(8, 2, 'haha')
);
$expected_result = '012test567haha0123456789';
Indices in $replacements are expected not to have overlaps.
I have been trying to write my own solution, split the original array into multiple pieces based on sections which needs to be replaced or not, and finally combine them:
echo str_replace_with_indices($string, $replacements);
// outputs the expected result '012test567haha0123456789'
function str_replace_with_indices ($string, $replacements) {
$string_chars = str_split($string);
$string_sections = array();
$replacing = false;
$section = 0;
foreach($string_chars as $char_idx => $char) {
if ($replacing != (($r_idx = replacing($replacements, $char_idx)) !== false)) {
$replacing = !$replacing;
$section++;
}
$string_sections[$section] = $string_sections[$section] ? $string_sections[$section] : array();
$string_sections[$section]['original'] .= $char;
if ($replacing) $string_sections[$section]['new'] = $replacements[$r_idx][2];
}
$string_result = '';
foreach($string_sections as $s) {
$string_result .= ($s['new']) ? $s['new'] : $s['original'];
}
return $string_result;
}
function replacing($replacements, $idx) {
foreach($replacements as $r_idx => $r) {
if ($idx >= $r[0] && $idx < $r[0]+$r[1]) {
return $r_idx;
}
}
return false;
}
Is there any more effective way to achieve the same result?
The above solution doesn't look elegant and feels quite long for string replacement.
Use this
$str = '01234567890123456789';
$rep = array(array(3,3,'test'), array(8,2,'haha'));
$index = 0;
$ctr = 0;
$index_strlen = 0;
foreach($rep as $s)
{
$index = $s[0]+$index_strlen;
$str = substr_replace($str, $s[2], $index, $s[1]);
$index_strlen += strlen($s[2]) - $s[1];
}
echo $str;

Simplify and Abstract my Code: Combining Strings

I want to combine strings in PHP. My script creates every possible combination like below.
$part1 = array('','d','n','s','g');
$part2 = array('a','e','o','oo');
$part3 = array('m','n','s','d','l','t','g','j','p');
$part4 = array('g','p','l','');
$part5 = array('g','p','l');
$part6 = array('a','e','o');
$part7 = array('d','l','r','');
$names = array();
foreach ($part1 as $letter1) {
foreach ($part2 as $letter2) {
foreach ($part3 as $letter3) {
foreach ($part4 as $letter4) {
foreach ($part5 as $letter5) {
foreach ($part6 as $letter6) {
foreach ($part7 as $letter7) {
$names[] = $letter1 . $letter2 . $letter3 . $letter4 . $letter5 . $letter6 . $letter7;
}
}
}
}
}
}
}
But I am not happy with my solution. I is quick and dirty code. Is there a solution wich works with a flexible number of part arrays, so I can extend the script by e.g. $part8 easiely? (without changing the loop construction)
Recursive one:
function buildNames( $parts, $chars = ''){
// Nothing to do, shouldn't happen
if( !count( $parts)){
return array();
}
$names = array();
$part = array_shift( $parts);
// Max level, we can build final names from characters
if( !count( $parts)){
foreach( $part as $char){
$names[] = $chars . $char;
}
return $names;
}
// "We need to go deeper" and build one more level with remembered chars so far
foreach( $part as $char){
$names = array_merge( $names, buildNames( $parts, $chars . $char));
}
return $names;
}
$parts = array( $part1, $part2, $part3, $part4, $part5, $part6, $part7);
$names = buildNames( $parts);
From head, from scratch, comment if something, but idea should be good
You could reduce this problem to six cartesian products:
cartesianProduct($part1,
cartesianProduct($part2,
cartesianProduct($part3,
cartesianProduct($part4,
cartesianProduct($part5,
cartesianProduct($part6, $part7))))));
function cartesianProduct($p1, $p2) {
$ret = array();
foreach($p1 as $l1)
foreach($p2 as $l2)
$ret[] = $l1 . $l2;
return $ret;
}

Categories