建立於: 1年前 ( 更新: 1年前 )
隨意用Laravel的tinker展示lookbehind功能
他需要固定長度,我們可以抓括號後的文字
原始內容為:
How fast is the car moving?
How far do you drive to work every day?
透過正規式lookbehind,只看How fast及How far後的字
(?<=How\s\w{4}\s).+|(?<=How\s\w{3}\s).+
Laravel tinker畫面
php artisan tinker
Psy Shell v0.11.8 (PHP 8.1.11 — cli) by Justin Hileman
>>> $re = '/(?<=How\s\w{4}\s).+|(?<=How\s\w{3}\s).+/m';
=> "/(?<=How\s\w{4}\s).+|(?<=How\s\w{3}\s).+/m"
>>> $str = 'How fast is the car moving?
... How far do you drive to work every day?
...
... ';
=> """
How fast is the car moving?\n
How far do you drive to work every day?\n
"""
>>>
>>> preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
=> 2
>>>
>>> // Print the entire match result
>>> var_dump($matches);
array(2) {
[0]=>
array(1) {
[0]=>
string(18) "is the car moving?"
}
[1]=>
array(1) {
[0]=>
string(31) "do you drive to work every day?"
}
}
如果您想研究正規式,推廌以下這個真的是「好讚」。
https://regex101.com/r/dhGbvw/1
No Comment
Post your comment