what is a ^?

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
mlecho
Forum Commoner
Posts: 53
Joined: Wed Feb 02, 2005 9:59 am

what is a ^?

Post by mlecho »

hi all...way back, i was having a problem with .DS_store files. I wanted some help to make php not "see" these files. So many of you helped resolve the issue, and the final key to the code was

Code: Select all

while(false!=($file=readdir($openDir))){
	if(!preg_match('/^\./', $file)){
		$files.= "<pict>$file</pict>";
		}
}
i have been studying why this works...and what i do not get is the ^ and the"/" and how they work together in definging the preg_match string. i know that the \ is an escape; and in the string , we are telling php that there is a "." by using the escape, but what is the role of the ^ symbol???

thanks
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

^ mean 'at the beginning' in this case, \. means . (otherwise the . would mean 'any character'). So that regular expression matches anything that doesn't have a . at the start.

The /s at the start and end are just delimiters that define the start and end of the expression.

It's just a complicated what of making sure $file isn't . or .. which are the current and parent directory links.

Personally I'd use:

Code: Select all

while(false!=($file=readdir($openDir))){
        if ($file=="." or $file=="..") { continue; } // If $file is . or .. skip to the next file.
        $files.= "<pict>$file</pict>";
}
NOTE: This assumes there won't be any hidden Unix files in the directory such as .htaccess or .passwd. If there could be, use the preg version.
mlecho
Forum Commoner
Posts: 53
Joined: Wed Feb 02, 2005 9:59 am

Post by mlecho »

thanks onion2k- very well done...i never knew that ^ could mean "starts with"....i actually have to use the preg version...originally, i used exactly what you suggested

if($file=="."...etc

but it would still show the .DS files....so i assume that it may have to do with the .htaccess files? Anyway, thanks for tunning me in...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

If you're only checking for a specific character in a specific position like you are here, I'd suggest not using regex. There's too much overhead involved to justify it. Instead I'd use string-array notation

Code: Select all

if ($file[0] == '.')
for example.
Post Reply