2013-12-18 35 views
-2
$a = "this is school of sachin"; 
$pattern = "sch"; 

我想从末尾获取匹配模式的位置。例如在这种情况下,sch匹配school - 所以模式的位置应该是3,即从结尾:如何获取从末尾匹配的字符串中的模式位置

如下所述,词学校的索引以这种方式排列,所以如果匹配sch比从匹配的单词(学校)和该模式的开始(从最后)开始的位置应该返回成功。

s c h o o l 
5 4 3 2 1 0 

^---^ 

匹配的模式。

我试过strpos(),但无法达到我的目的。

echo strpos($a, $pattern); // this is wrong 

根据我的问题,strpos()的输出应该是3。

+0

'这样的位置应该是3' - 你能解释一下吗? –

+1

@AmalMurali检查我的问题。我的意思是说,如果sch与学校匹配,那么我将比较匹配模式的最后一个索引。 –

+0

@AmalMurali我希望你明白我的问题? –

回答

2
<?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)"); 
    } 
} 
?> 
+0

有没有更简单的方法? –

+0

@RishabhRaj我已经更新了我的答案。我认为第二种方法很简单。 – 2013-12-18 14:15:30

+0

完美,但它会适用于非英文字符? http://3v4l.org/OPeu8这里字符串有一个荷兰字符,因此你的代码不起作用 –

1

不受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; 

注意,它会发现第一次出现,从左边开始,因此,例如 'schschool'会输出6.

+0

http://3v4l.org/DYWAP它不起作用 –

+0

你期望从这个例子中得到什么结果? – Kei

+0

谢谢你的答案kei但我想输出3。 –

1

注 - 这也告诉你,如果找到的话是完整的单词或不
看看 - 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; 
    } 
    } 
+1

它不会。你的代码会输出'13',但是OP需要'3'。 –

+0

我猜他想要的是单词的位置 – 2013-12-18 14:16:18

+0

现在它返回3 – 2013-12-18 14:39:12

1

使用正则表达式与word boundaries\b)的发现,提供的模式相匹配的词然后使用捕获组捕获所有模式后的所有内容。然后,只需返回字符串的长度:

$a = "this is school of sachin"; 
if (preg_match('/\b(sch(\w+))\b/', $a, $matches)) { 
    echo strlen($matches[2]); // => 3 
} 

如果你也想考虑非英文字符,那么你可以使用u修改:图案

$a = "this is sachinùs school of sachin"; 
if (preg_match('/\b(sch(\w+))\b/u', $a, $matches)) { 
    echo strlen($matches[2]); // => 3 
} 
+0

@RishabhRaj:很高兴得到了帮助。旁注:如果你还想检查它是否是一个完整的单词,你可以简单地检查'$ pattern == $是否匹配[1]'。请参阅[示例](https://eval.in/80610)。 –

相关问题