Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matching the regular expression with the whole string

Tags:

regex

php

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 ???

like image 760
Nauman Bashir Avatar asked Dec 12 '22 17:12

Nauman Bashir


2 Answers

Anchor the ends.

/^...$/
like image 106
Ignacio Vazquez-Abrams Avatar answered Jan 06 '23 18:01

Ignacio Vazquez-Abrams


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";
}

Output:

^hello world^   match
my ^hello world^        doesn't match
like image 22
Toto Avatar answered Jan 06 '23 17:01

Toto