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
Related
How can I achieve php char count with php :
input : bbbvvvvzzxxc
output : 3b4v2z2xc
I try this code :
$str = "aabbbccaaaac";
$arr1 = str_split($str);
$count=1;
foreach($arr1 as $key=>$char) {
if($key==0){
$pre=$char;
}
if($pre==$char){
$count++;
} else{
$count=1;
$pre=$char;
}
echo $pre.'---'.$char.'__';
if($pre != $char){
echo $char. $count ;
} else {
// echo $char;
}
}
but not working :
its simple to set count of character
$str = "aabbbccaaaac";
$arr1 = str_split($str);
$count=0;
$pre = '';
$result = ''; // our result string
foreach($arr1 as $char){
if($char == $pre){
$count++;
}else{
if($count > 0){ // To check whether it was the first iteration
$result .= $count.$pre;
}
$count = 1;
$pre = $char;
}
}
$result .= $count.$pre; // For last iteration
echo $result;
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 ) );
?>
<?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";
}
}
?>
I want to cut text in array but I have no idea to cut this
I try strstr() but it not true.
I try
$ff='';
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$ff .= $row['fav'] . ",";
}
if( strpos( $ff, "_" )) {
$text = strstr($ff, '_');
echo $text;
}
$ff ='A_0089,A_5677,B_4387,A_B_5566,'
I want output show
0089,5677,4387,B_5566,
Here is one example, using substr() with strpos():
$ff='A_0089,A_5677,B_4387,A_B_5566';
$items = explode(',', $ff);
foreach($items as $item) {
echo substr($item, strpos($item, '_')) . "\n";
}
The above code returns:
_0089
_5677
_4387
_B_5566
You're better off not building a string, but building an array. The way you build the string you have a dangling comma, which you do not want.
$ff = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$ff[] = $row['fav'];
}
foreach($ff as $item) {
echo substr($item, strpos($item, '_')) . "\n";
}
Based on your desire to keep the commas and create a string:
$ff='A_0089,A_5677,B_4387,A_B_5566,';
$items = explode(',', $ff);
foreach($items as $item) {
$new[] = substr($item, strpos($item, '_'));
}
$newFF = implode(',', $new);
echo $newFF;
returns:
_0089,_5677,_4387,_B_5566,
Probably this is what you are looking for
<?php
function test_alter(&$item1)
{
$pattern = '/^[A-Z]{1}[_]{1}/';
$item1 =preg_replace($pattern,"",$item1);
}
$ff="A_0089,A_5677,B_4387,A_B_5566,";
$nff=explode(",",$ff);
array_walk($nff, 'test_alter');
echo implode(",",$nff);
?>
Locked. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
I am trying to write a simple program which takes every 4th letter (not character) in a string (not counting spaces) and changes the case to it's opposite (If it's in lower, change it to upper or vice versa).
What I have so far:
echo preg_replace_callback('/.{5}/', function ($matches){
return ucfirst($matches[0]);
}, $strInput);
Expected Result: "The sky is blue" should output "The Sky iS bluE"
$str = 'The sky is blue';
$strArrWithSpace = str_split ($str);
$strWithoutSpace = str_replace(" ", "", $str);
$strArrWithoutSpace = str_split ($strWithoutSpace);
$updatedStringWithoutSpace = '';
$blankPositions = array();
$j = 0;
foreach ($strArrWithSpace as $key => $char) {
if (empty(trim($char))) {
$blankPositions[] = $key - $j;
$j++;
}
}
foreach ($strArrWithoutSpace as $key => $char) {
if (($key +1) % 4 === 0) {
$updatedStringWithoutSpace .= strtoupper($char);
} else {
$updatedStringWithoutSpace .= $char;
}
}
$arrWithoutSpace = str_split($updatedStringWithoutSpace);
$finalString = '';
foreach ($arrWithoutSpace as $key => $char) {
if (in_array($key, $blankPositions)) {
$finalString .= ' ' . $char;
} else {
$finalString .= $char;
}
}
echo $finalString;
Try this:
$newStr = '';
foreach(str_split($str) as $index => $char) {
$newStr .= ($index % 2) ? strtolower($char) : strtoupper($char);
}
it capitalize every 2nd character of string
<?php
$str = "The sky is blue";
$str = str_split($str);
$nth = 4; // the nth letter you want to replace
$cnt = 0;
for ($i = 0; $i < count($str); $i++) {
if($str[$i]!=" " && $cnt!=$nth)
$cnt++;
if($cnt==$nth)
{
$cnt=0;
$str[$i] = ctype_upper($str[$i])?strtolower($str[$i]):strtoupper($str[$i]);
}
}
echo implode($str);
?>
This code satisfies all of your conditions.
Edit:
I would have used
$str = str_replace(" ","",$str);
to ignore the whitespaces in the string. But as you want them in the output as it is, so had to apply the above logic.