說我有以下字符串:從文本字符串中提取第一個匹配項?
你好我的車是紅色的,我的鞋是藍色
我想匹配下面的話:
藍色,紅色,橙色,紫色
因此,它搜索這4個單詞的變量,並返回第一個 - 在我的例子中那麼返回的詞將是'紅'。但如果汽車是藍色的,那麼藍色的字首先會被返回,因爲這是第一個發現可能的匹配列表的字。
我該怎麼做?
說我有以下字符串:從文本字符串中提取第一個匹配項?
你好我的車是紅色的,我的鞋是藍色
我想匹配下面的話:
藍色,紅色,橙色,紫色
因此,它搜索這4個單詞的變量,並返回第一個 - 在我的例子中那麼返回的詞將是'紅'。但如果汽車是藍色的,那麼藍色的字首先會被返回,因爲這是第一個發現可能的匹配列表的字。
我該怎麼做?
區分大小寫。
<?php
$subject = "hello my car is blue and my shoe is blue";
$pattern = '/blue|red|orange|purple/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
if (!empty($matches)) {
echo 'Matched `' . $matches[0][0] . '` at index `' . $matches[0][1] . '`';
} else {
echo 'Nothing matched';
}
?>
不區分大小寫:
<?php
$subject = "hello my car is blue and my shoe is blue";
$pattern = '/blue|red|orange|purple/';
preg_match(strtolower($pattern), strtolower($subject), $matches, PREG_OFFSET_CAPTURE);
if (!empty($matches)) {
echo 'Matched `' . $matches[0][0] . '` at index `' . $matches[0][1] . '`';
} else {
echo 'Nothing matched';
}
?>
$string = 'hello my car is red and my shoe is blue';
$words = array ('blue', 'red', 'orange', 'purple');
function checkForWords ($a, $b) {
$pos = 0;
$first = 0;
$new_word = '';
foreach ($b as $value) {
$pos = strpos($a, $value);
# First match
if (!$first && $pos) {
$new_word = $value;
$first = $pos;
}
# Better match
if ($pos && ($pos < $first)) {
$new_word = $value;
$first = $pos;
}
}
return $new_word;
}
echo checkForWords ($string, $words);
對不起,沒有完全得到它:如果你的字符串是'我的車是藍色的,我的鞋是藍色的',那麼你應該怎麼樣ld會被退回嗎? – raina77ow
藍色,它會找到第一個並返回 – Latox
好的,但是,那麼問題是什麼?這兩個示例都是相同的代碼。 – raina77ow