开发者

What mean [^>] in regex preg php?

开发者 https://www.devze.com 2023-04-06 02:51 出处:网络
Example code: <?php $html = <<< html <p><a href=\"http://www.google.com\" title=\"10\">google.com</a></p>

Example code:

<?php
$html = <<< html
<p><a href="http://www.google.com" title="10">google.com</a></p>
<p><a href="http://www.cade.com" title="11">cade.com</a></p>
html;

echo preg_replace('#<p><a href\="([^>]+)" title="([^>]+)">([^&开发者_StackOverflow中文版gt;]+)</a></p>#','<p>$1 - $2</p>',$html);
?>

It works fine but i would like to know what [^>] means. I know that

  • + = 1 or more;
  • () = subpatterns;

But I don't know about ^>


It means any character other than >


^, when placed at the start of a character class ([) means any character EXCEPT what's in the class.

In your code, that would mean it would match any character except >.


It means that it should match any other character than >. It also means that the person that wrote this code and tried to parse HTML with regex didn't read the Bible and will very soon regret it.


It means any character apart from >.

(Side note: it is not usually a good idea to use regex to parse HTML.)


[^>] means a set of characters including all characters but >.


You have it in the PHP documentation for PCRE regex syntax

First, you have a list of meta-characters. You can check there to find the meaning of characters in regexes.

Concerning your question we find that:

  • The [ sign starts a character class definition, finished by ].
  • The use of ^ as the first character of a character class negates the character class.
  • > isn't a meta-character.

So, [^>] is any character that isn't >

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号