Jump to content

Match title case or uppercase instances only of a word


lindellfoth

Recommended Posts

Hi

 

I need to find all instances of a word in some text that is either in title case or uppercase but ignoring all lowercase instances. The function is used to locate surnames within the text. The problem is that some surnames eg "Law" are the same as common ordinary words so I need to find "Law" and "LAW" but not "law", so I can reduce the number of irrelevant results.

 

My current code uses preg_match_all in case insensitive mode, but if I simply make it case sensitive then the user will only find "Law" or "LAW", depending on which version they entered. I think there is a function or regular expression to change the first letter of a word to uppercase, but I don't want to change it, just locate instances already existing in the text.

 

Currently the code is:

$pattern='/.{0,'.$prechars.'}\b'.$surname.'\b.{0,'.$endchars.'}/is';

preg_match_all($pattern, $page_text, $match);

 

Anyone out there got any ideas? All help much appreciated.

Thanks for the suggestion, but won't that match any uppercase or title case word?

 

I need to match a specific word, input by the user. So if the user inputs the name "Law" for example, I need to find all instances of that particular word as title case ie "Law" or uppercase ie "LAW", but not instances that are all lowercase ie "law".

 

 

I would just make the search term exactly what you are looking for -

 

$surname = ucfirst($surname) .'|'. strtoupper($surname);
$pattern="/\b($surname)\b/s";

 

For your example, $pattern would be: /\b(Law|LAW)\b/s

Thanks for the suggestion, but won't that match any uppercase or title case word?

 

I need to match a specific word, input by the user. So if the user inputs the name "Law" for example, I need to find all instances of that particular word as title case ie "Law" or uppercase ie "LAW", but not instances that are all lowercase ie "law".

 

Yeah sorry.  Didn't read closely enough.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.