简体   繁体   中英

not repeating character from string in php

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();

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

If you want to get all the unique characters of a string you should use count_chars(). Documentation here

It should be set to mode 3 to get all the unique characters. I used your product title in this example:

$product_title = 'AABBBCCCDDEEEEEFFFFFGGGGFFFFHHHHIIIKKLLLXXXY';

$product_title = count_chars($product_title, 3);

print_r($product_title);

Output looks like this: 输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM