1.从一个字符串中 突出某个单词
这是一个非常有用的在一个字符串中匹配出某个单词
并且突出它,非常有效的搜索结果
<!DOCTYPE html>
<html>
<head>
<title>te</title>
</head>
<body>
<?php
$text = '轻松学习PHP基础知识,了解PHP中的变量、变量的类型、常量等概念,认识PHP中的运算符,掌握PHP中顺序结构、条件结构、循环结构三种语言结构语句。' ;
$output = str_replace ( 'PHP', '<span style="background:#5fc9f6">PHP</span>' , $text );
echo $output ;
?>
</body>
</html>
对于规定的字符串没有必要用正则表达式
输出结果:
2.移除图片的链接
<?php
$str = '
<a href="http://www.jobbole.com/">jobbole</a>其他字符
<a href="http://www.sohu.com/">sohu</a>
<a href="http://www.sohu.com/"><img src="http://www.fashion-press.net/img/news/3176/mot_06.jpg" /></a>
<br>';
//echo preg_replace("/(<a.*?>)(<img.*?>)(<\/a>)/", '$2', $str);
echo preg_replace("/(<a.*?>)(<img.*?>)(<\/a>)/", '\2', $str);
>
?>
3.从HTML文档中获得全部图片
<?php
set_time_limit(0);
$conn=fsockopen('Host',80,$errno,$errstr,30);
if(!$conn){
die('连接失败');
}
//说话,协议
$httpstr="GET uri HTTP/1.1\r\n";
$httpstr.="Host: Host\r\n";
$httpstr.="Connection: Close\r\n\r\n";
fwrite($conn,$httpstr,strlen($httpstr));
$res="";
while(!feof($conn)){
$res.=fread($conn,1024);
}
fclose($conn);
//我要找的该页面的图片img src ,使用正则表达式
$reg1='/<img alt="[^"]*" title="[^"]*" src="([^"]*)"/i';
preg_match_all($reg1,$res,$arr1);
//把$arr1[1], 遍历并取出各个图片的 url-主机部分=uri
foreach($arr1[1] as $imgurl){
//echo '<br/>'.$imgurl;
$imguri=str_replace("http://host","",$imgurl);
//再次发出请求要图片
$conn=fsockopen("host",80,$errno,$errstr,30);
//组织httpstr
$httpstr="GET $imguri HTTP/1.1\r\n";
$httpstr.="Host: host\r\n";
$httpstr.="Connection: Close\r\n\r\n";
//发出请求 img
fwrite($conn,$httpstr,strlen($httpstr));
$res2="";
while(!feof($conn)){
$res2.=fread($conn,1024);
}
fclose($conn);
$pos=strpos($res2,"\r\n\r\n");
$imgres=substr($res2,$pos+12);
$fileinfo=pathinfo($imguri);
file_put_contents("./path/".$fileinfo['basename'],$imgres);
sleep(2);
}
die('成功取出图片');