如何使用php爆炸单词

时间:2014-10-20 10:44:17

标签: php regex regex-negation

基于 luas Bangunan:xxx 的方式如何在php或爆炸中取词 例如,我有字符串

$string ="                 Kondisi Properti            : Bagus                    Dilengkapi Perabotan      : Unfurnished                    Sertifikat    : Lainnya                        Daya Listrik          : 2200 Watt                           Kamar Tidur         : 3/1                   Kamar Mandi      : 2/1                  **Luas Bangunan      : 92** m&sup2;                     Luas Tanah     : 126 m&sup2;                  Jumlah Lantai      : -<br>                 Kondisi Properti            : Bagus Sekali                       Dilengkapi Perabotan      : Unfurnished                    Sertifikat    : SHM - Sertifikat Hak Milik                         Daya Listrik          : 6600 Watt                       Saluran Telepon          : 1                        Garasi          : 3                             Kamar Tidur         : 4/1                   Kamar Mandi      : 3/1                  **Luas Bangunan      : 300** m&sup2;                     Luas Tanah     : 228 m&sup2;                 Jumlah Lantai      : 2.5                          ";

e.g。我想采取每一个&#34; Luas bangunan:xxx &#34;

2 个答案:

答案 0 :(得分:0)

嗯,这是一个特定的需求。在你的位置,我会用空格$ array = explode(&#39;&#39;,$ string)来爆炸字符串,用foreach($ array作为$ key =&gt; $ value)探索数组,并测试每个值如果它与Luas匹配strpos($ value,&#39; Luas&#39;)。因此,当它与Luas&#39;匹配时,您应该使用if条件进行测试,该条件接受数组中接下来的3个索引,然后在这个分离的数组上连接并保存这4个单词。

就像这样:

$array = explode(' ',$string);
$match = 'Luas';
$matchesArray = array();

foreach($array as $key => $value){
    //this var must word just like a temporary helper
    $target = '';
    //test each word
    if(strpos($value,$match) === true){

        //lets take the next word, 2 dots and the other word
        for($counter = 0;$counter <= 3;$counter++){
            //here we may construct our target phrase
            $nextWordsIndex = $key+$counter;
            $target.= $array[$nextWordsIndex].' ';
        }
        //but after the loop? Yes! we should take our target ready with 3 words
        $matchesArray[] = $target;
    }
}
//Now you should have a matchesArray with your wanted Information in each index.

答案 1 :(得分:0)

使用 - &gt;尝试这些解决方案preg_match_allpreg_split,我放了两个,因为我没有完全按照你的意愿行事:))

<?php

$string =" Kondisi Properti : Bagus Dilengkapi Perabotan : Unfurnished Sertifikat : Lainnya Daya Listrik : 2200 Watt Kamar Tidur : 3/1 Kamar Mandi : 2/1 Luas Bangunan : 92 m² Luas Tanah : 126 m² Jumlah Lantai : -
Kondisi Properti : Bagus Sekali Dilengkapi Perabotan : Unfurnished Sertifikat : SHM - Sertifikat Hak Milik Daya Listrik : 6600 Watt Saluran Telepon : 1 Garasi : 3 Kamar Tidur : 4/1 Kamar Mandi : 3/1 Luas Bangunan : 300 m² Luas Tanah : 228 m² Jumlah Lantai : 2.5 ";

preg_match_all("/Luas Bangunan : [0-9]+/",$string,$out);

echo "<pre>";
print_r($out);


$keywords = preg_split("/Luas Bangunan : [0-9]+/" ,$string );
echo "<pre>";
print_r($keywords);