I am getting the woo-commerce product title of the first character using wp-query but I have to get repeating and my OUTPUT is AABBBCCCDDEEEEEFFFFFGGGGFFFFHHHHIIIKKLLLXXXY but I want only one character not repeating a character. My desired output should be like "ABCDEFGHIKLXYZ"
$category_query_args = array('post_type' => 'product','posts_per_page' => -1,'post_status' => 'publish','orderby' => 'title','order' => 'ASC',); $category_query = new WP_Query($category_query_args); while($category_query->have_posts()):$category_query->the_post();
//Product Title $title = get_the_title(); $firstChar = substr($title,0,1);echo $firstChar; endwhile; wp_reset_query();CodePudding user response:
I'm using the example string as source, the first part is only to have an array. Just remember the last character. When it comes to the next character, only echo it if it is different to the last.
$s = 'AABBBCCCDDEEEEEFFFFFGGGGFFFFHHHHIIIKKLLLXXXY';
$a = preg_split('//', $s, -1, PREG_SPLIT_NO_EMPTY);
print_r($a);
$last = '';
foreach($a as $c) {
if ($c != $last) {
echo $c;
$last = $c;
}
}
CodePudding user response:
If you want to get all the unique characters of a string you should use count_chars().