使用正则表达式匹配给定单词中的子字符串(撇号)


Matching a substring (an apostrophe) in a given word using regex

我有一个服务器应用程序,它可以查找俄语单词中的重音所在。最终用户编写一个单词жажда。服务器从另一个服务器下载一个页面,其中包含用撇号表示的每个大小写/变化的应力,如жа'жда。我需要在下载的页面中找到那个单词。

在俄语中,重音总是写在元音之后。到目前为止,我一直在使用一个正则表达式,它是所有可能组合的分组(жа'жда|жа。有没有一个更优雅的解决方案,只使用正则表达式模式,而不是制作一个创建所有这些组合的PHP脚本?

编辑:

  1. 我有一个词
  2. 下载的页面包含字符串жа'жда。(注意撇号,我不知道撇号在哪里单词是)
  3. 我想用撇号来匹配这个词(жа'жда

附言:到目前为止,我已经有了一个PHP脚本来创建字符串(жа'жда|Жажд。

如果我理解你的问题,有这些选项‌​')其中一个在下载的页面上,我需要找出它是哪一个这可能适合您的需求:

<pre>
<?php
$s = "d'isorder|di'sorder|dis'order|diso'rder|disor'der|disord'er|disorde'r|disorder'|disorde'";
$s = explode("|",$s);
print_r($s);
$matches = preg_grep("@[aeiou]'@", $s);
print_r($matches);  

运行示例:https://eval.in/207282

嗯。。。你这样可以吗?

<?php
function find_stresses($word, $haystack) {
    $pattern = preg_replace('/[aeiou]/', ''0''?', $word);
    $pattern = "/'b$pattern'b/";
    // word = 'disorder', pattern = "diso'?rde'?r"
    preg_match_all($pattern, $haystack, $matches);
    return $matches[0];
}
$hay = "something diso'rder somethingelse";
find_stresses('disorder', $hay);
// => array(diso'rder)

您没有指定是否可以有多个匹配,但如果不能,您可以使用preg_match而不是preg_match_all(更快)。例如,在意大利语中,我们有àncoraancòra:P

显然,如果使用preg_match,结果将是字符串而不是数组。

基于您的代码,以及不调用任何函数和排除无序的要求。我想这就是你想要的。我添加了一个测试向量。

<pre>
<?php
// test code
$downloadedPage = "
there is some disorde'r
there is some disord'er in the example
there is some di'sorder in the example
there also' is some order in the example
there is some disorder in the example
there is some dso'rder in the example
";
$word = 'disorder';
preg_match_all("#".preg_replace("#[aeiou]#", "$0'?", $word)."#iu"
    , $downloadedPage
    , $result
);
print_r($result);
$result = preg_grep("#'#"
    , $result[0]
);
print_r($result);
// the code you need
$word = 'also';
preg_match("#".preg_replace("#[aeiou]#", "$0'?", $word)."#iu"
    , $downloadedPage
    , $result
);
print_r($result);
$result = preg_grep("#'#"
    , $result
);
print_r($result);

工作演示:https://eval.in/207312