preg_match作用

int  preg_match( string pattern, string subject [, array matches [, int  flags]] )
在  subject 字符串中搜索与 pattern给出的 正则表达式相匹配的内容。
如果提供了  matches,则其会被搜索的结果所填充。$matches[0] 将包含与整个模式匹配的文本, $matches[1] 将包含与第一个捕获的括号中的子模式所匹配的文本,以此类推。
flags 可以是下列标记:
PREG_OFFSET_CAPTURE如果设定本标记,对每个出现的匹配结果也同时返回其附属的字符串 偏移量。注意这改变了返回的 数组的值,使其中的每个单元也是一个数组,其中第一项为匹配字符串,第二项为其 偏移量。本标记自PHP 4.3.0 起可用。
flags 参数来自 PHP 4.3.0 起可用。
preg_match() 返回 pattern 所匹配的 次数。要么是  0 次(没有匹配)或  1 次,因为  preg_match() 在第一次匹配之后将停止搜索。如果出错  preg_match() 返回FALSE。

编辑本段从 URL 中取出域名

<?php
// 从 URL 中取得主机名
preg_match("/^(http:\/\/)?([^\/]+)/i", "http://www.***.net/index.html", $matches);
$host = $matches[2];
// 从主机名中取得后面两段
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>
本例将输出:
domain name is: PPP.NET

编辑本段搜索单词“web”

<?php
/* 模式中的 \b 表示单词的边界,因此只有独立的 "web" 单词会被匹配,
* 而不会匹配例如 "webbing" 或 "cobweb" 中的一部分 */
if (preg_match ("/\bweb\b/i", "PHP is the  web scripting language of choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
if (preg_match ("/\bweb\b/i", "PHP is the  website scripting language of choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
?>

编辑本段在文本中搜索“php”

<?php
// 模式定界符后面的 "i" 表示不区分大小写字母的搜索
if (preg_match ("/php/i", "PHP is the web scripting language of choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
?>
<?php
require('/libs/Smarty.class.php');
$smarty = new Smarty;
//$smarty->force_compile = true;
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;
$smarty->assign("Name","Fred Irving Johnathan Bradley Peppergill",true);
$smarty->assign("FirstName",array("John","Mary","James","Henry"));
$smarty->assign("LastName",array("Doe","Smith","Johnson","Case"));
$smarty->assign("Class",array(array("A","B","C","D"), array("E", "F", "G", "H"),
array("I", "J", "K", "L"), array("M", "N", "O", "P")));
$smarty->assign("contacts", array(array("phone" => "1", "fax" => "2", "cell" => "3"),
array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234")));
$smarty->assign("option_values", array("NY","NE","KS","IA","OK","TX"));
$smarty->assign("option_output", array("New York","Nebraska","Kansas","Iowa","Oklahoma","Texas"));
$smarty->assign("option_selected", "NE");
$smarty->display('index.tpl');
?>

编辑本段取得当前时间

<?php
//需要匹配的字符串。date函数返回当前时间。 "现在时刻:2012-04-20 07:31 am"
$content = "现在时刻:".date("Y-m-d h:i a");
//匹配日期和时间.
if (preg_match ("/\d{4}-\d{2}-\d{2} \d{2}:\d{2} [ap]m/", $content, $m))
{
echo "匹配的时间是:" .$m[0]. "\n"; //"2012-04-20 07:31 am"
}
//分别取得日期和时间
if (preg_match ("/([\d-]{10}) ([\d:]{5} [ap]m)/", $content, $m))
{
echo "当前日期是:" .$m[1]. "\n"; //"2012-04-20"
echo "当前时间是:" .$m[2]. "\n"; //"07:31 am"
}
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值