Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression for a word

Tags:

regex

php

I am doing a string parsing problem in PHP. I want a regular expression for a word in a dictionary. The word can contain only A-Z and a-z. I came up with this regex but this seems to be not working. Can someone help.

$regexp = "/[A-z]+/";
if(preg_match($regexp,$buffer)){    
   print $buffer . "<BR>";
}

Adding rkt's comment for eadibility

currently using this regex

$regexp = "/[A-Za-z]+/";

but still lot of irrelevant words are getting printed , for eg .

a.new,#quickbar a.new{color:#ba0000} enwiki:resourceloader:filter:minify-css:5:f2a9127573a22335c2a9102b208c73e7 wgNamespaceNumber=0;
wgAction="view";
wgPageName="Roger_Federer";
wgMainPageTitle="‌​Main Page";
wgWikimediaMobileUrl="http:\/\/en.m.wikipedia.org\/wiki";
document.writeln("\x3cdiv id=\"localNotice\"\x3e\x3cp\x3e\x3c/p\x3e\n\x3c/div\x3e");
like image 322
rkt Avatar asked Feb 24 '23 22:02

rkt


2 Answers

If you want to match a whole word only...

/\b[A-Z]+\b/i
like image 102
alex Avatar answered Mar 01 '23 22:03

alex


Besides the problem that Limo Wan Kenobi noted, your regex doesn't do what you think it does.

/[A-Za-z]+/

All this checks is that a letter, either case, appears somewhere in the input. If your input looks like this:

1111112222222333333333A333333444444555555567

It will still match.

What you are looking for is this regular expression:

/^[A-Za-z]+$/

This will match the beginning of the string, then one or more letters, and finally the end of the string. Now, there's no room for anything except letters!

like image 21
Mike Caron Avatar answered Mar 02 '23 00:03

Mike Caron