I am trying to write a function that will take a string and return a substring. Best to show by example:
I want to return the first word or words in the string that are all capital letters. For example, if the string is:
This sentence HAS THREE WORDS in a row that are all caps.
I want the expression to return "HAS THREE WORDS"
If the string is
This sentence HAS THREE WORDS in a row that are all caps and ANOTHER all caps word
it should find only "HAS THREE WORDS" and ignore any other words or letters that are all
caps.
I've been trying this pattern which doesn't work:
[\bA-Z]+^[\bA-Z]
Please help!
Thanks
need help creating the correct regex pattern
Moderator: General Moderators
- prometheuzz
- Forum Regular
- Posts: 779
- Joined: Fri Apr 04, 2008 5:51 am
Re: need help creating the correct regex pattern
Try:
Code: Select all
[A-Z]+(?:\s+[A-Z]+)+Re: need help creating the correct regex pattern
Very close. But if the sentence is this:
This sentence HAS THREE WORDS In a row that are all caps.
It finds
HAS THREE WORDS I
I want only consecutive words that are all caps.
BTW, what is correct way to code this in PHP? Is this right?
function get_dateline($str) {
return preg_grep('[A-Z]+(?:\s+[A-Z]+)+',$str);
}
This sentence HAS THREE WORDS In a row that are all caps.
It finds
HAS THREE WORDS I
I want only consecutive words that are all caps.
BTW, what is correct way to code this in PHP? Is this right?
function get_dateline($str) {
return preg_grep('[A-Z]+(?:\s+[A-Z]+)+',$str);
}
- prometheuzz
- Forum Regular
- Posts: 779
- Joined: Fri Apr 04, 2008 5:51 am
Re: need help creating the correct regex pattern
Then you need to add a word-boundary (\b) at the end.tbarmann wrote:Very close. But if the sentence is this:
This sentence HAS THREE WORDS In a row that are all caps.
It finds
HAS THREE WORDS I
I want only consecutive words that are all caps.
No, preg_match(...)tbarmann wrote:BTW, what is correct way to code this in PHP? Is this right?
function get_dateline($str) {
return preg_grep('[A-Z]+(?:\s+[A-Z]+)+',$str);
}