PHP在foreach循环中替换多个字符串

时间:2017-08-24 18:04:43

标签: php string replace

我抓住了一个页面的来源,其中包含列中列出的大量PDF链接(文件)。 simple_php_dom.php

SELECT groupID
FROM UserGroups
WHERE groupID IN(
  SELECT groupID
  FROM UserGroups
  WHERE userid IN (<list of all userids here>)
  GROUP BY groupID
  HAVING COUNT(*) = <count of userid list here>
) GROUP BY groupID
HAVING COUNT(*) = <count of userid list here>

我需要在foreach循环中重命名它们

SELECT
  groupID
FROM
  UserGroups ug
  INNER JOIN
  (SELECT groupID countof FROM UserGroups GROUP BY groupID HAVING COUNT(*) = <list length>) countedGroups
  ON ug.groupID = countedGroups.GroupID
WHERE
  ug.UserID IN (<list of user ids>) 
GROUP BY groupID
HAVING COUNT(*) = <list length>

例如,TALB是ALBANY的缩写,TAP是亚太地区的缩写,依此类推。

我有一个与缩写相对应的名称列表,但不确定如何在循环中重命名它们?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:4)

您可以将替换列表放在数组中:

<?php    
/*
$list = [];   
$list[] = "TALB20170826D-\$A$$-RA11.pdf";
$list[] = "TAP$20170826D-\$A$$-RA11.pdf";
$list[] = "TASD20170826D-\$A$$-RA11.pdf";
$list[] = "TAUA20170826D-\$A$$-RA11.pdf";
$list[] = "TAUB20170826D-\$A$$-RA11.pdf";
$list[] = "TAUC20170826D-\$A$$-RA11.pdf";
$list[] = "TAUD20170826D-\$A$$-RA11.pdf";
$list[] = "TBTP20170826D-\$A$$-RA11.pdf";
$list[] = "TCBY20170826D-\$A$$-RA11.pdf";
*/
$list = $html->find('a');
$abbr = [
    "TALB",
    "TAP",
    // ...
];
$replacements = [
    "ALBANY",
    "Asia Pacific",
    // ...
];
foreach ($list as &$el) {
    $el->href = str_replace($abbr, $replacements, $el->href);
}

Demo

或者,将它们全部保存在一个关联数组中(顺序无关紧要,丢失的项目不会被替换,没有错误):

<?php    
/*$list = [];   
$list[] = "TALB20170826D-\$A$$-RA11.pdf";
$list[] = "TAP$20170826D-\$A$$-RA11.pdf";
$list[] = "TASD20170826D-\$A$$-RA11.pdf";
$list[] = "TAUA20170826D-\$A$$-RA11.pdf";
$list[] = "TAUB20170826D-\$A$$-RA11.pdf";
$list[] = "TAUC20170826D-\$A$$-RA11.pdf";
$list[] = "TAUD20170826D-\$A$$-RA11.pdf";
$list[] = "TBTP20170826D-\$A$$-RA11.pdf";
$list[] = "TCBY20170826D-\$A$$-RA11.pdf";*/
$list = $html->find('a');
$abbr = [
    "TALB" => "ALBANY",
    "TAP" => "Asia Pacific",
];
foreach ($list as &$el) {
    $el->href = strtr($el->href, $abbr);
}

Demo

或者使用array_map(),也许你会觉得它更清洁一点:

$list = array_map(function($el) use($abbr) {
    return strtr($el, $abbr);
}, $list);