Intekhab Khan
Intekhab Khan

Reputation: 1863

All caps string with space in php

I got to extract string like "THE NEED OF FOLLOWING A RELIGION " from string. I extracted individual words like THE , NEED, OF... but I need complete string of capital letter like "THE NEED OF FOLLOWING A RELIGION" but not able to do so, please help.

preg_match_all("/[A-Z]*/", $html, $out);

Thanks

Upvotes: 0

Views: 70

Answers (3)

mohessaid
mohessaid

Reputation: 390

You can add the white space to your class like [A-Z ]. Now you can get all the strings in capitalized words but also a bench of single spaces.To avoid getting single spaces you use this ([A-Z]+[A-Z ]*[A-Z]) I added the () to capture the matched results. You can check it in action here.

Upvotes: 0

fronthem
fronthem

Reputation: 4139

Your regex just missed some condition of delimiter, which is

Words has to be either followed or leaded by a space.

Convert the sentence above to regex we get

[A-Z]*(?=\s)|(?<=\s)[A-Z]*

The regex above can interpret into either

\sWORD
WORD\s
\sWORD\s

See DEMO.

Upvotes: 0

Professor Abronsius
Professor Abronsius

Reputation: 33813

A very basic modification to the original code to find capitals of more than 1 at a time.

$str='This is a string WITH MIXED CASE words and WE ONLY WANT capitals';
preg_match_all("/[A-Z\s]{2,}/", $str, $out);
echo '<pre>',print_r($out,true),'</pre>';

outputs:

Array
(
    [0] => Array
        (
            [0] =>  WITH MIXED CASE 
            [1] =>  WE ONLY WANT 
        )

)

Upvotes: 3

Related Questions