简体   繁体   English

preg_replace函数用于PHP中的多个匹配

[英]preg_replace function for multiple matches in PHP

I am trying to get the base64 code for the insert image string using summer note js editor. 我正在尝试使用Summer note js编辑器获取插入图像字符串的base64代码。

I manage to get this 我设法得到这个

preg_replace('#<img\ssrc="data:image/([\w]+);base64,([a-zA-Z0-9+/-_=]+)"\sstyle="width:\s[0-9]+px;">#',"IMAGE REMOVED FROM CHROME\r\n", $content,-1, $counter);

AS well as a few variations depending on 以及一些变化,具体取决于

The position of the style and data-filename and src are always changing depending on different browsers and so i have a few variations. 样式和数据文件名以及src的位置总是根据不同的浏览器而变化,因此我有一些变化。

1) Are there easier way to do this? 1)有更简单的方法吗?

Like if i have all components of img src, style and data-filename , i will just match the string? 就像我有img src,style和data-filename的所有组件一样,我将匹配字符串吗? I can create all the variations but if i were to do $content = preg_replace 10 times for 10 different variations, isn't it extremely slow just to find one match? 我可以创建所有变体,但是如果我要为10个不同的变体做10次$ content = preg_replace,仅找到一个匹配就不是很慢吗? And it becomes increasingly slower if my $string is extremely long. 如果我的$ string太长,它将变得越来越慢。

2) I need to pull out the base64 string to save it as a image, how can i use the regex above to help me to fopen, fwrite, fclose? 2)我需要拉出base64字符串以将其另存为图像,我该如何使用上面的正则表达式来帮助我进行fopen,fwrite,fclose?

Thanks in advanced. 提前致谢。

You might use something like this: 您可能会使用以下内容:

<img(\s+src="data:image/([\w]+);base64,([\w+/-_=]+)")?(\s+style="width:\s*([\d]+)px;")?\s*>

You can look at this working example . 您可以看一下这个工作示例

This way, it covers the absence of src and/or style attributes. 这样,它涵盖了src和/或style属性的缺失。
It's up to you to eventually refine it to: 您最终需要将其优化为:

  • change the 2 attribute groups to non-capturing, depending on how you find them useful or not 将2个属性组更改为非捕获属性,具体取决于您认为它们是否有用
  • also make their contents partially optional, or even optionally richer (eg style might include other properties) 也使它们的内容部分可选,甚至可选地更丰富(例如, style可能包括其他属性)

Some additional points: 其他一些要点:

  • in order to face any case, I replaced \\s by \\s+ between attributes, and at the opposite by \\s* inside of style 为了面对任何情况,我在style之间用\\s+替换了\\s ,而在style内部则用\\s*替换了
  • I simplified [a-zA-Z0-9+/-_=]+ and [0-9]+ expressions, which become [\\w+/-_=]+ and [\\d]+ 我简化了[a-zA-Z0-9+/-_=]+[0-9]+表达式,它们分别变为[\\w+/-_=]+[\\d]+
  • I added capturing parenthesis around this last one (from your question, seems that you need to get width when available) 我在最后一个括号附近添加了括号(从您的问题来看,似乎需要在可用时获取宽度)

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

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