Jul
6
PHP Regex Extract Directiory from Full Path
July 6, 2008 |
This code snippet uses PHP Regex - ereg(), which is based on the extended POSIX regular expression implementation. It extracts directory from pull path.
<html>
<head><title>Extracting directiories from full paths</title></head>
<body>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="value" value="<? print $_POST ['value']; ?>"/><br/>
<input type="submit" value="Submit" /><br/><br/>
<?php
if ( $_SERVER['REQUEST_METHOD'] == "POST" ) {
$mystr = $_POST['value'];
if ( ereg( '^\/(.*)\/([^\/]+$|$)', $mystr, $matches ) ) {
echo "The directory is: /$matches[1]";
}
}
?>
</form>
</body>
</html>
Regular Expression Explanation:
|
^ |
the beginning of the line, followed by … |
|
\/ |
a slash, then … |
|
( |
the beginning of the group that captures … |
|
. |
any character … |
|
* |
found zero, one, or many times … |
|
) |
the end of the group, followed by … |
|
\/ |
a slash, then … |
|
( |
the beginning of a group that contains … |
|
[ |
a character class … |
|
^ |
that doesn't include … |
|
\/ |
a slash … |
|
] |
|
|
+ |
found at least one time, followed by … |
|
$ |
the end of the line … |
|
| |
or … |
|
$ |
the end of the line (without the [^\/]+ stuff). |
Similar Posts
- PHP Regex Extract Filename from Full Path
- PHP Regex - Extract Filenames from Full Path
- PHP Regex Extract Username from Email Address
- PHP Regex - Validate Email Address
- Validate URL Using PHP Regex
- PHP Regex Validate IP address
- PHP Regex Remove Whitespace from HTML


































