|
użytkowników online: 14
|
OPINIE UŻYTKOWNIKÓW
|
Prawdziwa skarbnica wiedzy na temat tworzenia stron WWW i nie tylko. Korzystam z porad praktycznie codziennie, jest mi to niezbędne w mojej pracy. Sam zajmuję się tworzeniem serwisów, ale porady pisane przez Darka sa dla mnie nieocenioną pomocą! Proste, czytelne i zrozumiałe dla każdego! Czekam na więcej!
Krzysztof Szypulski
KESS - projektowanie stron
|
|
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net
[Spis]
[A]
[B]
[C]
[D]
[E]
[F]
[G]
[H]
[I]
[J]
[K]
[L]
[M]
[N]
[O]
[P]
[Q]
[R]
[S]
[T]
[U]
[V]
[X]
[W]
[Z]
preg_match (PHP 3 >= 3.0.9, PHP 4, PHP 5) preg_match -- Perform a regular expression match Descriptionmixed preg_match ( string pattern, string subject [, array &matches [, int flags [, int offset]]] )
Searches subject for a match to the regular
expression given in pattern.
If matches is provided, then it is filled with the
results of search. $matches[0] will contain the text
that matched the full pattern, $matches[1] will have
the text that matched the first captured parenthesized subpattern, and so
on.
flags can be the following flag:
- PREG_OFFSET_CAPTURE
If this flag is passed, for every occurring match the appendant string
offset will also be returned. Note that this changes the return value
in an array where every element is an array consisting of the matched
string at offset 0 and its string offset into
subject at offset 1. This
flag is available since PHP 4.3.0 .
The flags parameter is available since
PHP 4.3.0.
Normally, the search starts from the beginning of the subject string. The
optional parameter offset can be used to specify
the alternate place from which to start the search.
The offset parameter is available since
PHP 4.3.3.
Notatka:
Using offset is not equivalent to
passing substr($subject, $offset) to
preg_match() in place of the subject string, because
pattern can contain assertions such as
^, $ or
(?<=x). Compare:
preg_match() returns the number of times
pattern matches. That will be either 0 times
(no match) or 1 time because preg_match() will stop
searching after the first match. preg_match_all()
on the contrary will continue until it reaches the end of
subject.
preg_match() returns FALSE if an error occurred.
Podpowiedź:
Do not use preg_match() if you only want to check if
one string is contained in another string. Use
strpos() or strstr() instead as
they will be faster.
Przykład 1. Find the string of text "php" |
<?php
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
|
|
Przykład 2. Find the word "web" |
<?php
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>
|
|
Przykład 3. Getting the domain name out of a URL |
<?php
preg_match("/^(http:\/\/)?([^\/]+)/i",
"http://www.php.net/index.html", $matches);
$host = $matches[2];
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>
|
This example will produce:
|
See also preg_match_all(),
preg_replace(), and
preg_split().
User Contributed Notespatrick at procurios dot nl
29-Jan-2006 07:17
This is the only function in which the assertion \\G can be used in a regular expression. \\G matches only if the current position in 'subject' is the same as specified by the index 'offset'. It is comparable to the ^ assertion, but whereas ^ matches at position 0, \\G matches at position 'offset'.
bloopy.org
26-Jan-2006 12:18
Intending to use preg_match to check whether an email address is in a valid format? The following page contains some very useful information about possible formats of email addresses, some of which may surprise you: http://en.wikipedia.org/wiki/E-mail_address
Zientar
02-Jan-2006 04:54
With this function you can check your date and time in this format: "YYYY-MM-DD HH:MM:SS"
<?php
function Check_Date_Time($date_time)
{
if (preg_match("/^([123456789][[:digit:]]{3})-
(0[1-9]|1[012])-(0[1-9]|[12][[:digit:]]|3[01])
(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/",
$date_time, $part) && checkdate($part[2], $part[3], $part[1]))
{
return true;
}
else
{
return false;
}
}
$my_date_time = "2006-01-02 16:50:15";
if (Check_Date_Time($my_date_time))
{
echo "My date '".$my_date_time."' is correct";
}
else
{
echo "My date '".$my_date_time."' is incorrect";
}
?>
john at recaffeinated d0t c0m
27-Dec-2005 05:27
Here's a format for matching US phone numbers in the following formats:
###-###-####
(###) ###-####
##########
It restricts the area codes to >= 200 and exchanges to >= 100, since values below these are invalid.
<?php
$pattern = "/(\([2-9]\d{2}\)\s?|[2-9]\d{2}-|[2-9]\d{2})"
. "[1-9]\d{2}"
. "-?\d{4}/";
?>
max99x [at] gmail [dot] com
06-Nov-2005 06:11
Here's an improvement on the URL detecting function written by [rickyale at ig dot com dot br]. It detects SRC, HREF and URL links, in addition to URLs in CSS code, and Javascript imports. It also understands html entities(such as &) inside URLs.
<?php
function get_links($url) {
if( !($body = @file_get_contents($url)) ) return FALSE;
$pattern = "/((@import\s+[\"'`]([\w:?=@&\/#._;-]+)[\"'`];)|";
$pattern .= "(:\s*url\s*\([\s\"'`]*([\w:?=@&\/#._;-]+)";
$pattern .= "([\s\"'`]*\))|<[^>]*\s+(src|href|url)\=[\s\"'`]*";
$pattern .= "([\w:?=@&\/#._;-]+)[\s\"'`]*[^>]*>))/i";
preg_match_all ($pattern, $body, $matches);
return (is_array($matches)) ? $matches:FALSE;
}
?>
$matches[3] will contain Javascript import links, $matches[5] will contain the CSS links, and $matches[8] will contain the regular URL/SRC/HREF HTML links. To get them all in one neat array, you might use something like this:
<?php
function x_array_merge($arr1,$arr2) {
for($i=0;$i<count($arr1);$i++) {
$arr[$i]=($arr1[$i] == '')?$arr2[$i]:$arr1[$i];
}
return $arr;
}
$url = 'http://www.google.com';
$m = get_links($url);
$links = x_array_merge($m[3],x_array_merge($m[5],$m[8]));
?>
rebootconcepts.com
05-Nov-2005 04:33
Guarantee (one) trailing slash in $dir:
<?php
$dir = preg_match( '|(.*)/*$|U', $dir, $matches );
$dir = $matches[1] . '/';
?>
For whatever reason,
<?php $dir = preg_replace( '|^([^/]*)/*$|', '$1/', $dir ); ?>
and
<?php $dir = preg_replace( '|/*$|U', '/', $dir ); ?>
don't work (perfectly). The match, concat combo is the only thing I could get to work if there was a '/' within $dir (like $dir = "foo/bar";
phpnet_spam at erif dot org
27-Oct-2005 07:37
Test for valid US phone number, and get it back formatted at the same time:
function getUSPhone($var) {
$US_PHONE_PREG ="/^(?:\+?1[\-\s]?)?(\(\d{3}\)|\d{3})[\-\s\.]?"; //area code
$US_PHONE_PREG.="(\d{3})[\-\.]?(\d{4})"; // seven digits
$US_PHONE_PREG.="(?:\s?x|\s|\s?ext(?:\.|\s)?)?(\d*)?$/"; // any extension
if (!preg_match($US_PHONE_PREG,$var,$match)) {
return false;
} else {
$tmp = "+1 ";
if (substr($match[1],0,1) == "(") {
$tmp.=$match[1];
} else {
$tmp.="(".$match[1].")";
}
$tmp.=" ".$match[2]."-".$match[3];
if ($match[4] <> '') $tmp.=" x".$match[4];
return $tmp;
}
}
usage:
$phone = $_REQUEST["phone"];
if (!($phone = getUSPhone($phone))) {
//error gracefully :)
}
1413 at blargh dot com
06-Oct-2005 10:41
For a system I'm writing, I get MAC addresses in a huge number of formats. I needed something to handle all of the following:
0-1-2-3-4-5
00:a0:e0:15:55:2f
89 78 77 87 88 9a
0098:8832:aa33
bc de f3-00 e0 90
00e090-ee33cc
::5c:12::3c
0123456789ab
and more. The function I came up with is:
<?php
function ValidateMAC($str)
{
preg_match("/^([0-9a-fA-F]{0,2})[-: ]?([0-9a-fA-F]{0,2})[-: ]?([0-9a-fA-F]{0,2})[-: ]?([0-9a-fA-F]{0,2})[-: ]?([0-9a-fA-F]{0,2})[-
: ]?([0-9a-fA-F]{0,2})[-: ]?([0-9a-fA-F]{0,2})$/", $str, $arr);
if(strlen($arr[0]) != strlen($str))
return FALSE;
return sprintf("%02X:%02X:%02X:%02X:%02X:%02X", hexdec($arr[1]), hexdec($arr[2]), hexdec($arr[3]), hexdec($arr[4]), hexdec($arr[5]
), hexdec($arr[6]));
}
$testStrings = array("0-1-2-3-4-5","00:a0:e0:15:55:2f","89 78 77 87 88 9a","0098:8832:aa33","bc de f3-00 e0 90","00e090-ee33cc","
bf:55:6e:7t:55:44", "::5c:12::3c","0123456789ab");
foreach($testStrings as $str)
{
$res = ValidateMAC($str);
print("$str => $res<br>");
}
?>
This returns:
0-1-2-3-4-5 => 00:01:02:03:04:05
00:a0:e0:15:55:2f => 00:A0:E0:15:55:2F
89 78 77 87 88 9a => 89:78:77:87:88:9A
0098:8832:aa33 => 00:98:88:32:AA:33
bc de f3-00 e0 90 => BC:DE:F3:00:E0:90
00e090-ee33cc => 00:E0:90:EE:33:CC
bf:55:6e:7t:55:44 =>
::5c:12::3c => 00:00:5C:12:00:3C
0123456789ab => 01:23:45:67:89:AB
tlex at NOSPAM dot psyko dot ro
22-Sep-2005 08:34
To check a Romanian landline phone number, and to return "Bucharest", "Proper" or "Unknown", I've used this function:
<?
function verify_destination($destination) {
$dst_length=strlen($destination);
if ($dst_length=="10"){
if(preg_match("/^021[2-7]{1}[0-9]{6}$/",$destination)) {
$destination_match="Bucharest";
} elseif (preg_match("/^02[3-6]{1}[0-9]{1}[1-7]{1}[0-9]{5}$/",$destination)) {
$destination_match = "Proper";
} else {
$destination_match = "Unknown";
}
}
return ($destination_match);
}
?>
paullomax at gmail dot com
06-Sep-2005 07:01
If you want some email validation that doesn't reject valid emails (which the ones above do), try this code (from http://iamcal.com/publish/articles/php/parsing_email)
function is_valid_email_address($email){
$qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
$dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
$atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
$quoted_pair = '\\x5c\\x00-\\x7f';
$domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d";
$quoted_string = "\\x22($qtext|$quoted_pair)*\\x22";
$domain_ref = $atom;
$sub_domain = "($domain_ref|$domain_literal)";
$word = "($atom|$quoted_string)";
$domain = "$sub_domain(\\x2e$sub_domain)*";
$local_part = "$word(\\x2e$word)*";
$addr_spec = "$local_part\\x40$domain";
return preg_match("!^$addr_spec$!", $email) ? 1 : 0;
}
webmaster at swirldrop dot com
26-Jul-2005 08:46
To replace any characters in a string that could be 'dangerous' to put in an HTML/XML file with their numeric entities (e.g. é for
|