字符串php旁边的数字

时间:2012-06-19 08:06:54

标签: php arrays

我有一个字符串“在那所房子里有9间卧室”,但它可能是其他任何东西,但卧室关键字将保留(床,床,卧室,卧室等)< - 这是$ search_array变量

我已使用explode

将其转换为数组

我需要找一个单词卧室,看看旁边是否有数字。

假设爆炸后我的阵列是 - (9,卧室,在,那个,房子),我怎么能检查旁边的数字

我已经使用了下面的代码及其内部函数,因此$ array =& $这 - > search_array

if($array =& $this->search_array){
$bedroom_keywords = array('bed', 'beds', 'bedroom', 'bedrooms');
foreach($this->bedroom_keywords as $beds)
        {   
            // if successful in assigning key find a 
            // number in next and previous positions
            if($key = array_search($beds, $array))
            {
                if($next = $array[$key+1])
                {
                    echo $next;
                }
                elseif($prev = $array[$key-1])
                {
                    echo $prev;
                }
            }
        }
}

但我得到了这个错误:

注意:未定义的偏移量:第92行/Users/User/Sites/parser.php中的2个9ad_type:

当我只使用2个代币时,即“9张床”。

有什么方法可以检查数组中是否有下一个/上一个值或做某事以使它能够正常工作?

感谢

4 个答案:

答案 0 :(得分:2)

我认为你应该检查阵列的长度,因为当你在“9张床”上运行这个功能时,键+ 1将是2,而数组只有位置0和1.你可以只添加一个条件在你内心的if-else条件下。

答案 1 :(得分:1)

您可以使用正则表达式执行此任务:

([0-9]+) +(bed|beds|bedroom|bedrooms)

会找到一个至少有一位数的数字,然后是任意数量的空格,然后是其中一个单词。

答案 2 :(得分:1)

使用正则表达式。例如,要从每个输入中获取床位数:

$inputs = array('1 bed', '22 beds', '1 bedROOM', '99   beDRooms', 'beds');
foreach($inputs as $input) {
    if (preg_match('/(\d+)\s+bed($|s|room|rooms)/i', $input, $matches)) {
        echo "$input => ".$matches[1]."\n";
    }
    else {
        echo "$input => **no match**\n";
    }
}

上面的正则表达式匹配一个或多个数字(我们要隔离),后跟任意数量的空格,后跟你提到的任何触发词。

See it in action

答案 3 :(得分:0)

假设你有数组

$bedroom_keywords = array('bed', 'beds', 'bedroom', 'bedrooms');

你要检查关键词,这也是你可以做的

foreach($bedroom_keywords as $keyword){
    // here you will check it from you actuall array
     if(in_array($keyword ,'yoyr array')){
         echo 'success';
    }
}

希望这将有所帮助