解决方案我在寻找: 我想在文本字符串结果中重新排列单词,以便将作业标题从字符串的末尾移动到每个行项目的字符串的开头。
目前,我正在从外部医疗数据库查询( $ query )检索数据。但是,我无法对数据库或MySQL查询语句本身进行任何更改。
检索 $ query ,然后通过以下命令将结果放入 $ data 数组中:
while($row = mysql_fetch_assoc($query)){$data[] = $row;}
然后我将 $ data 数组中的所有职位名称更改为大写,如下所示:
$job_01 = 'anesthesiologist';
$job_02 = 'dentist';
$job_03 = 'general practitioner';
$job_04 = 'internist';
$job_05 = 'lawyer';
$job_06 = 'manager';
$job_07 = 'pediatrician';
$job_08 = 'psychiatrist';
$replace_01 = 'ANESTHESIOLOGIST';
$replace_02 = 'DENTIST';
$replace_03 = 'GENERAL PRACTITIONER';
$replace_04 = 'INTERNIST';
$replace_05 = 'LAWYER';
$replace_06 = 'MANAGER';
$replace_07 = 'PEDIATRICIAN';
$replace_08 = 'PSYCHIATRIST';
$searchArray = array($job_01, $job_02, $job_03, $job_04, $job_05, $job_06, $job_07, $job_08);
$replaceArray = array($replace_01, $replace_02, $replace_03, $replace_04, $replace_05, $replace_06, $replace_07, $replace_08);
for ($i=0; $i<=count($data)-1; $i++) {
$line[$i] = str_ireplace($searchArray, $replaceArray, $data[$i]));
}
最终输出采用以下行项目文本字符串格式:
示例查询结果(4个订单项)
California Long time medical practitioner - ANESTHESIOLOGIST 55yr
New York Specializing in working with semi-passive children - PEDIATRICIAN (doctor) 42yr
Nevada Currently working in a new medical office - PSYCHIATRIST 38yr
Texas Represents the medical-liability industry - LAWYER (attorney) 45yr
我想重新安排这些结果,以便我可以通过将职称移动到每个订单项的开头,以下列格式将数据输出给我的用户如:
期望的结果(通常超过1000件)
ANESTHESIOLOGIST - California Long time medical practitioner - 55yr
PEDIATRICIAN - New York Specializing in working with semi-passive children - (doctor) 42yr
PSYCHIATRIST - Nevada Currently working in a new medical office - psychiatrist 38yr
LAWYER - Texas Represents the medical-liability industry - lawyer (attorney) 45yr
理想情况下,如果可能的话,将年龄移至文本字符串结果的开头,结果如下:
理想结果
55yr - ANESTHESIOLOGIST - California Long time medical practitioner
42yr - PEDIATRICIAN - New York Specializing in working with semi-passive children - (doctor)
38yr - PSYCHIATRIST - Nevada Currently working in a new medical office - psychiatrist
45yr - LAWYER - Texas Represents the medical-liability industry - lawyer (attorney)
答案 0 :(得分:1)
您可以使用正则表达式来提取和重新排列数组:
for ($i=0; $i<=count($data)-1; $i++) {
$line[$i] = str_ireplace($searchArray, $replaceArray, $data[$i]));
// variant a, complete line
if(preg_match_all('/(.*)\s+-\s+(.*)\s+(\d+)yr$/', $line[$i],$matches)) {
$line[$i] = $matches[3][0].'yr - '.$matches[2][0].' - '.$matches[1][0];
// variant b, a line with age, but no jobtitle
} elseif(preg_match_all('/(.*)\s+-\s+(\d+)yr$/', $line[$i],$matches)) {
$line[$i] = $matches[2][0].'yr - '.$matches[1][0];
// variant c, no age
} elseif(preg_match_all('/(.*)\s+-\s+(.*)$/', $line[$i],$matches)) {
$line[$i] = $matches[2][0].' - '.$matches[1][0];
}
// in other cases (no age, no jobtitle), the line is not modified at all.
}