Reputation: 1752
im kinda strumped in a situation where i need to match a whole string with a regular expression rather than finding if the pattern exists in the string.
suppose if i have a regular expression
/\\^^\\w+\\$^/
what i want is that the code will run through various strings , compare the strings with the regular expression and perform some task if the strings start and end with a ^.
Examples
^hello world^ is a match
my ^hello world^ should not be a match
the php function preg_match matches both of the results
any clues ???
Upvotes: 4
Views: 8541
Reputation: 91518
Here is a way to do the job:
$strs = array('^hello world^', 'my ^hello world^');
foreach($strs as $str) {
echo $str, preg_match('/^\^.*\^$/', $str) ? "\tmatch\n" : "\tdoesn't match\n";
}
^hello world^ match
my ^hello world^ doesn't match
Upvotes: 5
Reputation: 241
Another pattern is: ^\^[^\^]*\^$
if you want match "^hello world^" and not "hello ^world^" , while \^[^\^]*\^
if you want match "^hello world^" and world in the "hello ^world^" string.
For Will: ^\^.*\^$
this match also "^hello^wo^rld^" i think isn't correct.
Upvotes: 0
Reputation: 455470
You can use the regex:
^\^[\w\s]+\^$
^
is a regex meta-character which is used as start anchor. To match a literal ^
you need to escape it as \^
.
So we have:
^
: Start anchor\^
: A literal ^
[\w\s]+
: space separated words.\^
: A literal ^
$
: End anchor.Upvotes: 2
Reputation: 3680
Actually, ^\^\w+\^$
will not match "^hello world^" because you have two words there; the regex is only looking for a single word enclosed by "^"s.
What you are looking for is: ^\^.*\^$
This will match "^^", "^hello world^", "^a very long string of characters^", etc. while not matching "hello ^world^".
Upvotes: 2