PHP正则表达式取文本中间内容。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP正则表达式取文本中间内容。相关的知识,希望对你有一定的参考价值。

不太懂正则表达式,而且又是初学php,向各位高手或达人求段函数。示例代码如下(里面其他的内容还很多也不仅仅是一张图片):
<img src="http://127.0.0.1/test.jpg">
要求写个单独的函数参数为 html内容,返回 图片 路径 http://127.0.0.1/test.jpg 的数组。 谢谢!!!

比如说这样添加的计时器:
Dim Timer1 As New Timer
要在合适的地方开始,比如窗体Load事件中,这样:
Timer1.Interval = 1000 '单位毫秒,1000毫秒=1秒
Timer1.Enabled = True '启用计时器

然后在代码窗口上方下拉列表里选择Timer1的Tick事件,自动添加代码:
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
End Sub

这是计时器触发的事件,每秒触发一次,在这里面输入循环判断是否有日程即可。提示:可以用Now对象获取当前的日期和时间。

参考技术A

给你个例子吧。。

结果

本回答被提问者采纳
参考技术B 这是n年前写的采集下载图片,剪切加水印的功能的类中的函数,有些图片是带参数的url,一般的都考虑到

你参考下
public function getRemoteImg($url,$imgWidth="",$imgHeight="",$cutPX=0, $cutPY=0,$waterImg="",$waterPX=0,$waterPY=0,$savePath="")

if(empty($url)) return "";
if(empty($savePath))
$savePath="../image/data/remoteImages/";

else

$savePath='../image/'.$savePath."/";



if(!file_exists($savePath)) mkdir($savePath,0777);
$savePath.=date('Y-m').'/';
if(!file_exists($savePath)) mkdir($savePath,0777);
$filename=$savePath.strrchr($url,"/");
$filename=str_replace('//','/',$filename);

$cutPX=(int)$cutPX;
$cutPY=(int)$cutPY;

/*读取图片 */
if(!stripos('lankii'.$url,'http://') && !stripos('lankii'.$url,'https://'))$url='http://'.$url;
$imginfo = @getimagesize($url);
if(!$imginfo)return '';exit;
$img_width = $imginfo[0];//取得图片的宽
$img_height = $imginfo[1];//取得图片的高

switch($imginfo[2])//取得图片的格式

case 1:$im = imagecreatefromgif($url);break;
case 2:$im = imagecreatefromjpeg($url);break;
case 3:$im = imagecreatefrompng($url);break;



if(empty($imgWidth)||empty($imgHeight))
//如果截取了,新图片需要减去这部分,要不然会有黑色块
$new_img_width = $img_width;
$new_img_height =$img_height;

else
$new_img_width =(int)$imgWidth;
$new_img_height =(int)$imgHeight;


// 先建立一个 新的空白图片档
$newim = imagecreatetruecolor($new_img_width, $new_img_height);

// 输出图要从哪边开始x, y , 原始图要从哪边开始 x, y , 要输多大 x, y(resize) , 要抓多大 x, y
imagecopyresampled($newim, $im, 0, 0, $cutPX, $cutPY, $new_img_width, $new_img_height, $img_width-$cutPX, $img_height-$cutPY);

//水印代码
//设定混色模式
if(!empty($waterImg))
imagealphablending($newim,true);
$waterinfo = getimagesize($waterImg);
$ww = $waterinfo[0];//取得图片的宽
$wh = $waterinfo[1];//取得图片的高

switch($waterinfo[2])//取得图片的格式

case 1:$water = imagecreatefromgif($waterImg);break;
case 2:$water = imagecreatefromjpeg($waterImg);break;
case 3:$water = imagecreatefrompng($waterImg);break;



//水印位置
if((int)$waterPX==0)
$waterPX=(($new_img_width-$ww)/2<=0)?0:($new_img_width-$ww)/2;

if((int)$waterPY==0)
$waterPY=(($new_img_height-$wh)/2<=0)?0:($new_img_height-$wh)/2;


//拼合水印
imagecopy ($newim,$water,$waterPX,$waterPY,0,0,$ww,$wh);


//保存图片
imagejpeg($newim,$filename,100);
// 资源回收
imagedestroy($newim);
imagedestroy($im);

return str_replace('../image/',HTTP_CATALOG . 'image/',$filename);



public function exchangeImgRemoteToLocal($content="",$homeUrl,$replaceArr=array(),$repTxtArr=array(),$download=true,$imgWidth="",$imgHeight="",$cutPX=0, $cutPY=0,$waterImg="",$waterPX=0,$waterPY=0)
if(empty($content))return ''; exit;;

//if(!empty($waterImg) && !stripos($waterImg,'http://') && !stripos($waterImg,'https://'))$waterImg='http://'.$waterImg;
//是否下载远程图片
if($download)
$s='/<img(.*?)src="(.*?)(?=")/i';
if(preg_match_all($s,$content,$array)>0)

foreach($array[2] as $IR)
$mir="";
$mir=$IR;
$mir=str_ireplace('../','',$mir);
if(!stripos('lankii'.$mir,'http://')&&!stripos('lankii'.$mir,'https://'))$mir=$homeUrl.'/'.$mir;

$content= str_ireplace($IR,$this->getRemoteImg($mir,$imgWidth,$imgHeight,$cutPX, $cutPY,$waterImg,$waterPX,$waterPY),$content);




///替换符合规则的内容为指定内容
if(is_array($replaceArr)&&is_array($repTxtArr))

if(count($replaceArr)>0&&count($replaceArr)==count($repTxtArr))
if(trim(implode('',$replaceArr))!='')
$content=preg_replace($replaceArr,$repTxtArr,$content);



$content=preg_replace("/(<img)(.*?)src=(['\" ])?([0-9a-z\/\.:\?\#-]*)(['\" ])?(.*?)(\/>)/i",'[lankiiImgBegin] src="$4" [lankiiImgEnd]',$content);
$content=strip_tags($content);
$content=str_ireplace("[lankiiImgBegin]","<img",$content);
$content=str_ireplace("[lankiiImgEnd]","/>",$content);

return $content;

C# 正则表达式提取指定文本内的内容

直接上代码和如何使用

        /// <summary>
        /// 截取字符串中开始和结束字符串中间的字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="startStr">开始字符串</param>
        /// <param name="endStr">结束字符串</param>
        /// <returns>中间字符串</returns>
        public string SubstringSingle(string source, string startStr, string endStr)
        
            Regex rg = new Regex("(?<=(" + startStr + "))[.\\\\s\\\\S]*?(?=(" + endStr + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            return rg.Match(source).Value;
        
 
        /// <summary>
        /// (批量)截取字符串中开始和结束字符串中间的字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="startStr">开始字符串</param>
        /// <param name="endStr">结束字符串</param>
        /// <returns>中间字符串</returns>
        public List<string> SubstringMultiple(string source, string startStr, string endStr)
        
            Regex rg = new Regex("(?<=(" + startStr + "))[.\\\\s\\\\S]*?(?=(" + endStr + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            
            MatchCollection matches = rg.Matches(source);
 
            List<string> resList=new List<string>();
 
            foreach (Match item in matches)
                resList.Add(item.Value);
 
            return resList;
        

 用法如下:

string html="这里 Html 文本内容省略";
 
var text1 = regex.SubstringSingle(html, "<div id=\\"pagelet_timeline_main_column\\">", "<div id=\\"pagelet_sidebar\\"");
 
var text2 = regex.SubstringMultiple(html, "<div class=\\"_4-u2 _4-u8\\">", "<div class=\\"_1dnh\\">");


具体去自己体会吧,个人觉得很实用,这里是写成了扩展方法来调用的。

 

        /// <summary>
        /// 去除转义字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RemoveEscapeChar(this string str,int re=0)
        
            if (string.IsNullOrWhiteSpace(str))
                return "";
 
            if (re == 1) //不替换特殊字符
                return str;
 
            if (re == 2)  //不移除空格
                return str.Replace("\\n", "").Replace("\\t", "").Replace("\\r", "");
 
            return str.Replace("\\n", "").Replace("\\t", "").Replace("\\r", "").Replace(" ", "").Trim();
        


上面是去除页面中转义字符,换行符的一个扩展方法,去除后再配合正则来进行筛选很实用,我个人主要用在对请求得到的html 指定内容进行提取。

2020年1月15号补充:

在使用的过程中难免会遇到一些正则表达式的特殊符号例如下面这个文本

oL[289]( x[/42.934715] y[/31.199666] z[/-0.929894] u[/-0.20919151978424] v[/-0.04218084669353] w[/0.97696452557019] )

我们要提取出  [ ]  中的内容,那么在写的时候就要加上转义了,如下代码我分别提取文本中的x,y,z,u,v,w中的值 使用 \\\\ 进行特殊符号转义

string temp_x = SubstringSingle(str, "x\\\\[/", "\\\\]");
string temp_y = SubstringSingle(str, "y\\\\[/", "\\\\]");
string temp_z = SubstringSingle(str, "z\\\\[/", "\\\\]");
string temp_u = SubstringSingle(str, "u\\\\[/", "\\\\]");
string temp_v = SubstringSingle(str, "v\\\\[/", "\\\\]");
string temp_w = SubstringSingle(str, "w\\\\[/", "\\\\]");


这些就是需要注意的地方了,所以当你在提取时候如果有正则中特殊字符记得转义哈,不然会匹配不到的哦!
————————————————
版权声明:本文为CSDN博主「Syspan」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_40729514/article/details/95986966

以上是关于PHP正则表达式取文本中间内容。的主要内容,如果未能解决你的问题,请参考以下文章

易语言如何用正则表达式来读取制定的网页文本 最好源码上,谢谢

求个正则表达式,获取两个字中间的内容!比如“a123啊45,c”

易语言正则表达式

正则表达式对文本的部分替换

php用正则表达式怎么取双引号里面的内容??

Linux如何使用正则表达式命令?文本文件操作命令