Home Backend Development PHP Tutorial php正则婚配图片路径看preg_match_all()函数用法

php正则婚配图片路径看preg_match_all()函数用法

Jun 13, 2016 am 11:03 AM
array gt img jpg string

php正则匹配图片路径看preg_match_all()函数用法

php正则匹配图片路径看preg_match_all()函数用法.<p>先看php代码:</p><pre class="php" name="code">$ext = 'gif|jpg|jpeg|bmp|png';//罗列图片后缀从而实现多扩展名匹配 by http://www.k686.com 绿色软件$str = '<p><img src="/static/imghw/default1.png"  data-src="http://www.k686.com/data/soft_img/2010091101619.jpg"  class="lazy"  title="绿色软件" alt="绿色软件" onload="ResizeImage(this,860)" /></p>';preg_match_all("/(href|src)=([\"|']?)([^ \"'>]+\.($ext))\\2/i", $str, $matches);var_dump($matches);
Copy after login

?

以上代码执行后的结果为:

array(5) {  [0]=>  array(1) {    [0]=>    string(57) "src="http://www.k686.com/data/soft_img/2010091101619.jpg""  }  [1]=>  array(1) {    [0]=>    string(3) "src"  }  [2]=>  array(1) {    [0]=>    string(1) """  }  [3]=>  array(1) {    [0]=>    string(51) "http://www.k686.com/data/soft_img/2010091101619.jpg"  }  [4]=>  array(1) {    [0]=>    string(3) "jpg"  }}
Copy after login

?

?

<p>这里我们来温习下php手册上的函数说明:</p>
Copy after login
preg_match_all -- 进行全局正则表达式匹配说明int preg_match_all ( string pattern, string subject, array matches [, int flags] )在 subject 中搜索所有与 pattern 给出的正则表达式匹配的内容并将结果以 flags 指定的顺序放到 matches 中。 搜索到第一个匹配项之后,接下来的搜索从上一个匹配项末尾开始。 flags 可以是下列标记的组合(注意把 PREG_PATTERN_ORDER 和 PREG_SET_ORDER 合起来用没有意义): PREG_PATTERN_ORDER对结果排序使 $matches[0] 为全部模式匹配的数组,$matches[1] 为第一个括号中的子模式所匹配的字符串组成的数组,以此类推。 <?phppreg_match_all ("|<[^>]+>(.*)</[^>]+>|U",    "<b>example: </b><div align=left>this is a test</div>",    $out, PREG_PATTERN_ORDER);print $out[0][0].", ".$out[0][1]."\n";print $out[1][0].", ".$out[1][1]."\n";?>  本例将输出: <b>example: </b>, <div align=left>this is a test</div>example: , this is a test 因此,$out[0] 包含匹配整个模式的字符串,$out[1] 包含一对 HTML 标记之间的字符串。 
Copy after login

?

可能还是有点迷糊,继续测试,这次换用多个图片地址,就能看的一清二楚了.

<?php$ext = 'gif|jpg|jpeg|bmp|png';//罗列图片后缀从而实现多扩展名匹配 by http://www.k686.com 绿色软件$str = '<p><img src="/static/imghw/default1.png"  data-src="http://www.k686.com/data/soft_img/2010091101619.jpg"  class="lazy"  title="绿色软件" alt="绿色软件" onload="ResizeImage(this,860)" /></p><p><img src="/static/imghw/default1.png"  data-src="http://www.k686.com/data/soft_img/2010091029938.jpg"  class="lazy"  title="绿色软件" alt="绿色软件" onload="ResizeImage(this,860)" /></p><p><img src="/static/imghw/default1.png"  data-src="http://www.k686.com/data/soft_img/2010092839019.jpg"  class="lazy"  title="绿色软件" alt="绿色软件" onload="ResizeImage(this,860)" /></p>';preg_match_all("/(href|src)=([\"|']?)([^ \"'>]+\.($ext))\\2/i", $str, $matches);var_dump($matches);?>
Copy after login

?

?

结果为:

array(5) {  [0]=>  array(3) {    [0]=>    string(57) "src="http://www.k686.com/data/soft_img/2010091101619.jpg""    [1]=>    string(57) "src="http://www.k686.com/data/soft_img/2010091029938.jpg""    [2]=>    string(57) "src="http://www.k686.com/data/soft_img/2010092839019.jpg""  }  [1]=>  array(3) {    [0]=>    string(3) "src"    [1]=>    string(3) "src"    [2]=>    string(3) "src"  }  [2]=>  array(3) {    [0]=>    string(1) """    [1]=>    string(1) """    [2]=>    string(1) """  }  [3]=>  array(3) {    [0]=>    string(51) "http://www.k686.com/data/soft_img/2010091101619.jpg"    [1]=>    string(51) "http://www.k686.com/data/soft_img/2010091029938.jpg"    [2]=>    string(51) "http://www.k686.com/data/soft_img/2010092839019.jpg"  }  [4]=>  array(3) {    [0]=>    string(3) "jpg"    [1]=>    string(3) "jpg"    [2]=>    string(3) "jpg"  }}
Copy after login

?

?

对比下第一个简单的单图片例子,我们就更清楚需要哪一个元素了.一般情况下,我们是为了得到图片的真实直接路径,也就是 $matches[3] ,取出来做个foreach就可以继续下面的处理了.

?

实际上这个代码比较死板,正则可以改为:

preg_match_all('/<img (.*?)src=("|\'|\s)?(.*?)(?="|\'|\s)/',$str,$arr2);</pre alt="php正则婚配图片路径看preg_match_all()函数用法" ><p>?</p><p>其他不变.因为有些变态网站图片没有扩展名,就没辙了,所以换上面这个正则,管他什么扩展名,只要是img开头的,就跑不离是图片了.</p><pre class='brush:php;toolbar:false;'>	function getname($fileext){		if( !in_array($fileext,array('gif','jpg','jpeg','bmp','png')) ) $fileext = 'png';		return date('Ymdhis').rand(100, 999).'.'.$fileext;	}
Copy after login

?

这个是返回图片后缀,没有就默认png

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open img file How to open img file Sep 18, 2023 am 09:40 AM

Methods to open img files include using virtual optical drive software, using compression software, and using special tools. Detailed introduction: 1. Use virtual optical drive software to open, download and install a virtual optical drive software, right-click the img file, select "Open with" or "Associated Program", select the installed virtual optical drive software in the pop-up dialog box, virtual The optical drive software will automatically load the img file and use it as a disc image in the virtual optical drive. Double-click the disc icon in the virtual optical drive to open the img file and access its contents, etc.

How to convert PNG to JPG on Windows 11 How to convert PNG to JPG on Windows 11 May 12, 2023 pm 03:55 PM

How to Convert PNG to JPG on Windows 11 On Windows 10 and 11, you can use Microsoft's built-in Paint app to quickly convert image files. To convert a PNG image to JPG on Windows 11, use the following steps: Open File Explorer and navigate to the PNG image you want to convert. Right-click the image and select Open With > Draw from the menu. Your photo or image opens in the Paint app. Note the file size at the bottom of the screen. To convert a file from PNG to JPG, click File and select Save As > JPEG Image from the menu. When the file resource

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Fix: Can't open JPG files in Windows 11 Fix: Can't open JPG files in Windows 11 Apr 17, 2023 pm 12:37 PM

JPG is one of the most popular image file formats along with PNG. This is a lossy compressed image format ideal for websites. Therefore, many users save or convert images to JPG format. However, some users have stated that they are having issues opening JPG files in Windows 11 using the platform’s default Photos app. Therefore, these users cannot open, view and edit JPG format images in Windows 11. This is what one user said in a Microsoft forum post: When double-clicking a JPG file to open in Microsoft Photo, I receive the error The specified program cannot be found. This was purchased new about a month ago

Convert basic data types to strings using Java's String.valueOf() function Convert basic data types to strings using Java's String.valueOf() function Jul 24, 2023 pm 07:55 PM

Convert basic data types to strings using Java's String.valueOf() function In Java development, when we need to convert basic data types to strings, a common method is to use the valueOf() function of the String class. This function can accept parameters of basic data types and return the corresponding string representation. In this article, we will explore how to use the String.valueOf() function for basic data type conversions and provide some code examples to

How to open img file How to open img file Jul 06, 2023 pm 04:17 PM

How to open the img file: 1. Confirm the img file path; 2. Use the img file opener; 3. Select the opening method; 4. View the picture; 5. Save the picture. The img file is a commonly used image file format, usually used to store picture data.

How to convert char array to string How to convert char array to string Jun 09, 2023 am 10:04 AM

Method of converting char array to string: It can be achieved by assignment. Use {char a[]=" abc d\0efg ";string s=a;} syntax to let the char array directly assign a value to string, and execute the code to complete the conversion.

Let's talk about how to use php to easily convert WebP to JPG. Let's talk about how to use php to easily convert WebP to JPG. Mar 24, 2023 pm 02:57 PM

In recent years, with the continuous development of Web technology, WebP, a new image format, has gradually entered the field of vision of programmers and Web developers. The advantages of WebP cannot be ignored: small file size, high quality, high browser support, etc. But in some cases, we may need to convert WebP images into some other formats, such as JPG. So, how to use PHP to convert WebP to JPG?

See all articles