php 正则匹配 字符串href
时间: 2023-09-18 07:16:18 浏览: 36
可以使用以下正则表达式来匹配字符串中的 href:
```php
$pattern = '/href\s*=\s*[\"\']?([^\"\'>\s]+)/i';
```
这个表达式可以匹配以下几种情况:
- href="url"
- href='url'
- href=url
其中,url 可以包含字母、数字、下划线、短横线等字符。在 PHP 中,可以使用 preg_match_all() 函数来匹配所有的 href:
```php
$string = "这是一个字符串,其中包含 href='http://www.example.com' 和 href=\"https://www.example.org\"";
$pattern = '/href\s*=\s*[\"\']?([^\"\'>\s]+)/i';
preg_match_all($pattern, $string, $matches);
print_r($matches[1]);
```
输出结果为:
```
Array
(
[0] => http://www.example.com
[1] => https://www.example.org
)
```
其中,$matches[1] 就是匹配到的所有 href 的值。
相关问题
php正则匹配字符串中的中文
可以使用正则表达式来匹配字符串中的中文。以下是一个基本的 PHP 正则表达式示例,可以匹配字符串中的中文:
```
preg_match_all('/[\x{4e00}-\x{9fa5}]+/u', $str, $matches);
```
这个正则表达式会匹配所有的中文字符,并将它们存储在 `$matches` 数组中。其中,`$str` 是待匹配的字符串。`[\x{4e00}-\x{9fa5}]` 是一个 Unicode 范围,表示所有的中文字符。
如果你需要匹配的字符串中还包含其他字符,可以将正则表达式修改为:
```
preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9]+/u', $str, $matches);
```
这个正则表达式将匹配所有中文字符、字母和数字。
java 正则匹配字符串
Java中可以使用正则表达式来匹配字符串。正则表达式是一种用来描述、匹配和操作字符串的强大工具。你可以使用正则表达式来验证字符串是否符合某种模式、提取字符串中的特定内容等。
Java提供了正则表达式的支持,你可以使用java.util.regex包中的类来进行正则匹配。常用的类包括Pattern和Matcher。Pattern类用于表示一个正则表达式,Matcher类用于对字符串进行匹配。
下面是一个简单的示例,演示如何使用正则表达式匹配字符串:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String[] args) {
String input = "Hello, world!";
String pattern = "Hello";
// 创建Pattern对象,并编译正则表达式
Pattern regex = Pattern.compile(pattern);
// 使用Pattern对象创建Matcher对象
Matcher matcher = regex.matcher(input);
// 进行匹配操作
if (matcher.find()) {
System.out.println("字符串匹配成功");
} else {
System.out.println("字符串匹配失败");
}
}
}
```
运行上述代码,输出结果为"字符串匹配成功",说明输入字符串中包含了"Hello"这个子串。