tags:

views:

47

answers:

1

Hi,

I have this dynamic string

"ZAN ROAD HOG HEADWRAPS The most popular ZAN headwrap style-features custom and original artwork"

EDIT How can I check all the capital words then if I encountered a ucwords() or title case word then I will automatically add a '--' after the last capital word? Note: The capital words are the product name and the first ucwords() or title case word is the start of the product description.

I have this code right now but its not working at the moment:

<?php 
$str = preg_replace( '/\s+/', ' ', $sentence );
$words = array_reverse( explode( ' ', $str ) );
foreach ( $words as $k => $s ) {
    if ( preg_match( '/\b[A-Z]{5,}\b/', $s ) ) {
        $words[$k] = $s . " --";
        break;
    }
}
$short_desc = addslashes( trim( join( ' ', array_reverse( $words ) ) )); 
?>

Thanks in advance.

+2  A: 

You can do this:

$str = preg_replace('/^(?:\p{Lu}+\s+)+(?=\p{Lu}*\p{Ll})/u', '$0-- ', $str);

Here ^(?:\p{Lu}+\s+)+ describes a sequence of words at the begin of the string that are separated by whitespace where each word is a sequence of uppercase letters (\p{Lu}, see Unicode character properties). The look-ahead assertion (?=\p{Lu}*\p{Ll}) is just to ensure that there actually is something following that contains a lowercase letter.

Gumbo
Need a single whitespace after `--`
BoltClock
@BoltClock: Yep, thanks.
Gumbo
Nice a regex god :D Cool I will try it now. Thanks for the fast reply sir! :)
marknt15
Update: I think it misses some other sentence but I think it is close.
marknt15