简体   繁体   English

如何在 PHP 中使用 preg_match() 以相反的顺序从一堆文本中获取特定字符串

[英]How to get specific string from the bunch of texts in reverse order using preg_match() in PHP

Currently I am using below code for getting specific string from the texts.目前我正在使用下面的代码从文本中获取特定的字符串。

preg_match('~background(.*?).png~', $css_content, $output);

I use this code for getting specific text from bunch of the text.我使用此代码从一堆文本中获取特定文本。 This code works but it goes serially that is left to right.此代码有效,但它从左到右依次进行。
For example: Let's say following of texts例如:让我们说以下文本

"color:#fff; background:url('assets/imgages/background.png');" “颜色:#fff;背景:url('assets/imgages/background.png');”

Now I want to get text " background:url('assets/images/background.png "现在我想得到文本“ background:url('assets/images/background.png ”
The function preg_match() works like this:函数 preg_match() 的工作方式如下:
It first finds the "background" text that I've added in above function then it finds for ".png" text also added in function.它首先查找我在上述函数中添加的“背景”文本,然后查找也在函数中添加的“.png”文本。 This looks like it works left to right.这看起来像从左到右工作。 But I want to make it opposite that is right to left.但我想让它从右到左相反。
What I want to do is, function should find ".png" first and then it should be go for "background" text.我想要做的是,函数应该首先找到“.png”,然后它应该去寻找“背景”文本。

You can use so called positive look ahead .您可以使用所谓的积极展望

~(background...(?=\\.png)~ ~(背景...(?=\\.png)~

-> finds the background (if .png is after it) -> 找到背景(如果 .png 在它之后)

In your situation:在你的情况下:

preg_match('~background(.*?)(?=\.png)~', $css_content, $output);

You can test it here:你可以在这里测试:

https://regex101.com/r/kC2rO2/1 https://regex101.com/r/kC2rO2/1

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

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