简体   繁体   English

如何使用PHP正则表达式查找并返回字符串的一部分?

[英]How to use PHP Regular Expressions to find and return a portion of a string?

I would like to find and return a sentence that starts with "Find" and ends with "eBay.", but I cannot get it to work. 我想查找并返回一个以“ Find”开头并以“ eBay。”结尾的句子,但是我无法使其正常工作。 Here's what I have now: 这是我现在所拥有的:

if (preg_match("/^Find eBay\.$/", $post->post_content) == 1) {

                    $description = preg_grep("/^Find eBay\.$/", $post->post_content);

                } else {

                    $description = $this->trim_excerpt_without_filters($this->internationalize($post->post_content));

                }

Any advice would be great. 任何建议都很好。 Thanks! 谢谢!

Edit** 编辑**

This is the string I'm searching: 这是我正在搜索的字符串:

<p><a href="http://cgi.ebay.com/ebaymotors/?cmd=ViewItem&amp;_trksid=p3984.m1438.l2649&amp;item=110804005978&amp;sspagename=STRK%3AMEWAX%3AIT">here on eBay</a>Find this 1969 Chevrolet Camaro COPO 427 for sale in New York, .</p>

试试这个,。*表示任意数量的任何字符

/^Find.*eBay\.$/

Your example string doesn't start with "Find" nor end with "eBay", so it will not match your example string. 您的示例字符串不是以“查找”开头,也不是以“ eBay”结尾,因此它与您的示例字符串不匹配。

To match your example, you will need to use something like this: 为了匹配您的示例,您将需要使用以下内容:

/eBay\<\/a\>Find/

That will match a string that contains eBay</a>Find (though you could use just use a simple search for that instead of a regex). 它将匹配包含eBay</a>Find的字符串(尽管您可以使用简单的搜索来代替regex)。

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

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