如何在从末尾匹配的字符串中获取模式的位置
$a = "this is school of sachin";
$pattern = "sch";
I want to get the position of the pattern matched from the end. For example in this case, sch
matches school
-- so the position of the pattern should be 3, i.e. from the end:
as mentioned below the index for the word school are arranged in this manner,so if the match of sch
is successful than the position from the end of the word which is getting matched(school) and to the start of the pattern(from the end) should be returned.
s c h o o l
5 4 3 2 1 0
^---^
matched pattern.
I have tried strpos()
but could not make it to serve my purpose.
echo strpos($a, $pattern); // this is wrong
The output of strpos() should be 3 according to my question.
$ a =“这是sachin学校”;
$ pattern =“sch”; \ n code> pre>
我想得到从末尾匹配的模式的位置。 例如,在这种情况下, sch code>匹配 school code> - 因此模式的位置应为3,即从结尾开始: p>
如下所述,单词school的索引是以这种方式排列的,所以如果 sch code>的匹配成功,则匹配到匹配(学校)的单词结尾的位置和 应返回模式的开头(从结尾开始)。 p>
school
5 4 3 2 1 0
^ --- ^
code> pre>
匹配的模式。 em> p>
我已经尝试了 strpos() code>但是无法做到 为了我的目的。 p>
echo strpos($ a,$ pattern); //这是错的
code> pre>
根据我的问题,strpos()的输出应该是3。 strong> p>
<?php
$a = "this is school of sachin";
$pattern = "sch";
$words = explode(" ", $a);
$pattern = strrev($pattern);
foreach($words as $word){
$pos = strpos(strrev($word), $pattern);
if($pos !== false){
print($pos);
break;
}
}
?>
OR
<?php
$a = "this is sachinùs school of sachin";
$pattern = "sach";
if(preg_match("/[^ [:punct:]]*".$pattern."([^ [:punct:]]*)/u", $a, $match)){
print(mb_strlen($match[1], "UTF-8"));
if($pattern == $match[0]){
print(" (full word)");
}
}
?>
Without the whole approach suggested by Sharanya
$haystack = 'this is a verygood school of sachin';
$pattern = 'sch';
$match = strstr($haystack, $pattern);
for ($i = 0;$i < strlen($match);$i++) {
if ($match[$i] == ' ') {
$match = substr($match, 0, $i);
break;
}
}
$result = strlen($match) - strlen($pattern);
echo $result;
Note that it will find the FIRST occurence starting from left, so for example 'schschool' would output 6.
NOTE - This also, tells you if the found word is full word or not
Take a look - http://3v4l.org/i94Lr
$pattern = "sch";
$b = explode(' ','this is school of sachin');
$b = array_reverse($b);
for($i=0;$i < count($b);$i++){
if(strpos($b[$i],$pattern) !== false){
echo $i+1;
$full = ', not a full word';
if($b[$i] == $pattern){
$full = ', full word';
}
echo $full;
break;
}
}
Use a regular expression with word boundaries (\b
) to find the word that matches the supplied pattern and then capture everything after the pattern using a capturing group. Then, simply return the length of that string:
$a = "this is school of sachin";
if (preg_match('/\b(sch(\w+))\b/', $a, $matches)) {
echo strlen($matches[2]); // => 3
}
If you also want to account for non-English characters, then you can use the u
modifier:
$a = "this is sachinùs school of sachin";
if (preg_match('/\b(sch(\w+))\b/u', $a, $matches)) {
echo strlen($matches[2]); // => 3
}