如何在php中做下面的事情?
我有两个输入$ bankdata和$ databasedata。
问题:
将字符串中的单词与其他字符串单词相匹配
具有更多空格的字符串在以下情况下将被视为基本字符串:$ databasedata将被视为基本字符串,然后将其与每个单词的$ bankdata比较,然后将DHANA
和{{1}分开},然后重写
LAKSHMI
例如:
$bankdata = DHANA LAKSHMI K
答案 0 :(得分:1)
您好,@ Daoootim,此代码将检查另一个字符串中的单词,并将其替换为额外的空格。您需要做出更多条件,因为这非常简单。希望对您有所帮助。
$bankdata = 'P VENKATESWARARAO RAO' ;
$databasedata = 'PARELLA VENKATESWARARAORAO';
echo 'INPUT: ' . $databasedata . '<br>';
echo 'INPUT: ' . $bankdata . '<br>';
$inputArray1 = explode(' ',$bankdata);
$inputArray2 = explode(' ',$databasedata);
foreach ($inputArray1 as $word) {
if (strlen($word) > 1){
foreach ($inputArray1 as $reference) {
if ($reference != $word){
if (strpos($reference,$word) > 0) continue 2;
}
}
$databasedata = str_replace($word, $word." ",$databasedata);
}
}
foreach ($inputArray2 as $word) {
if (strlen($word) > 1){
foreach ($inputArray2 as $reference) {
if ($reference != $word){
if (strpos($reference,$word) > 0) continue 2;
}
}
$bankdata = str_replace($word, $word." ",$bankdata);
}
}
echo 'OUTPUT: ' . $databasedata . '<br>';
echo 'OUTPUT: ' . $bankdata . '<br>';
输入:PARELLA VENKATESWARA RAORAO
输入:P VENKATESWARA RAO RAO
输出:PARELLA VENKATESWARARAO RAO
输出:P VENKATESWARARAO RAO
答案 1 :(得分:1)
<?php
function swap(&$bankdata, &$databasedata)
{
// get the spaces from each word
// we use preg_replace to remove additional spaces in any of the words.
$bank_arr = explode(' ', preg_replace('/\s+/', ' ', $bankdata));
$data_arr = explode(' ' , preg_replace('/\s+/', ' ', $databasedata));
$bank_space_count = count($bank_arr);
$data_space_count = count($data_arr);
$fixUp = function ($words, $with)
{
$patterns = [];
$replacements = [];
foreach($with as $each_word) {
// skip single characters
if (strlen($each_word) == 1) {
continue;
}
$patherns[] = "/{$each_word}(\w\s+)?/";
$replacements[] = "$0 ";
}
return preg_replace($patherns, $replacements, $words);
};
if ($bank_space_count >= $data_space_count) {
$databasedata = $fixUp($databasedata, $bank_arr);
}
else {
$bankdata = $fixUp($bankdata, $data_arr);
}
}
$bankdata = 'DHANALAKSHMI K';
$databasedata = 'DHANA LAXMI KOILADA';
swap($bankdata, $databasedata);
var_dump($bankdata, $databasedata);
3v4l在这里
Edited 3v4l