简体   繁体   English

正则表达式:从标签获取宽度和高度

[英]Regex: Getting the width and height from a tag

I'm building a wysiwyg extension and have built a library for image uploading and handling. 我正在构建一个wysiwyg扩展,并已构建了一个用于图像上传和处理的库。 To further integrate in the code I want to extract some data from the wysiwyg output like so: 为了进一步集成到代码中,我想从所见即所得的输出中提取一些数据,如下所示:

$content = '<img class="left media-id-1657" src="someurl" width="113" height="97" />';
preg_match_all('/<[^>]*class="[^"]*\media-id-([0-9]{1,10})\b[^"]*"[^>]*>/i', $content, $matches);

This gives me the given id, which in this case is 1657 . 这给了我给定的id,在这种情况下为1657 It works great and no change is needed. 它运作良好,不需要任何更改。

But now I also need to get the width (and height). 但是现在我还需要获取宽度(和高度)。 But for some stupid reason I can't extract it. 但是出于某些愚蠢的原因,我无法提取它。 I came up with this: 我想出了这个:

/<[^>]*class="[^"]*\media-id-([0-9]{1,10})\b[^"]*width="([0-9]{1,10})"[^>]*>/i

But it's not doing what I want as it gives 0 matches. 但是它没有满足我的要求,因为它给出了0个匹配项。 http://regexr.com/3h14n http://regexr.com/3h14n

Try this one 试试这个

preg_match( '/width="(.*?)"/', $content, $matchesWidth);
preg_match( '/height="(.*?)"/', $content, $matchesHeight);
print_r($matchesWidth[1]); //Output 113
print_r($matchesHeight[1]); //Output 97

抱歉,经过一些玩耍已经知道了。

/<[^>]*class="[^"]*\media-id-([0-9]{1,10})\b[^"]*"[^>]*width="([0-9]{1,10})"[^>]*height="([0-9]{1,10})"[^>]*>/i

There are quotes in between the \\b and the width parts of the string, but not the regex. \\b和字符串的width部分之间有引号,但正则表达式则没有。

Does this work: 这个工作:

/<[^>]*class="[^"]*\media-id-([0-9]{1,10})\b.*width="([0-9]{1,10})"[^>]*>/i

If you need to do it all with one regex, this should work for the params in the current order: 如果您需要使用一个正则表达式来完成所有操作,那么这应该适用于当前顺序的参数:

<img class="\D+(\d+)".*?width="(\d+)" height="(\d+)"

That being said, if there are extra spaces between width, height or anything else it won't. 话虽如此,如果宽度,高度或其他任何东西之间都没有多余的空间,那就不会了。 You'll have to code for those issues, but if you are confident the data will always be in that format it will work. 您必须为这些问题编写代码,但是如果您确信数据将始终采用该格式,那么它将起作用。 Personally I would break it into 3 regexes. 我个人将其分为3个正则表达式。 Your current one and then for height and width very simple: 您当前的一个,然后对于高度和宽度非常简单:

width="(\d+)"
height="(\d+)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM