目标str_replace()只处理wp-admin中的一个元素


Target str_replace() to work on only one element in wp-admin

是否可以使用PHP的str_replace()函数仅针对页面中的选择div(例如通过ID或类标识)?

情况:我使用以下str_replace()函数将Wordpress Post Editor-Categories元框中的所有复选框转换为使用单选按钮,这样我的网站的作者只能在一个类别中发帖。

下面的代码正在工作(在WP3.5.1上),但它替换了同一页面上其他复选框元素的代码。有没有办法只针对代谢组这一类别?

// Select only one category on post page
if(strstr($_SERVER['REQUEST_URI'], 'wp-admin/post-new.php') || 
strstr($_SERVER['REQUEST_URI'], 'wp-admin/post.php'))
{
  ob_start('one_category_only');
}
function one_category_only($content) {
  $content = str_replace('type="checkbox" ', 'type="radio" ', $content);
  return $content;
}

您可以使用正则表达式来过滤带有ID的内容部分,然后使用str_replace,也可以使用DOMDocument和DOMXPath来扫描内容并操作输入元素:

// test content
$content = '<div id="Whatever"><div id="YOURID"><input type="checkbox" /></div><div id="OTHER"><input type="checkbox" /></div></div>';
function one_category_only($content) {
    // create a new DOMDocument
    $dom=new domDocument;
    // load the html
    $dom->loadHTML($content);
    // remove doctype declaration, we just have a fragement...
    $dom->removeChild($dom->firstChild);  
    // use XPATH to grep the ID 
    $xpath = new DOMXpath($dom);
    // here you filter, scanning the complete content 
    // for the element with your id:
    $filtered = $xpath->query("//*[@id = 'YOURID']");
    if(count($filtered) > 0) { 
        // in case we have a hit from the xpath query,
        // scan for all input elements in this container
        $inputs = $filtered->item(0)->getElementsByTagName("input");
        foreach($inputs as $input){
            // and relpace the type attribute
            if($input->getAttribute("type") == 'checkbox') {
                $input->setAttribute("type",'radio');
            }
        }
    }
    // return the modified html
    return $dom->saveHTML();
}
// testing
echo one_category_only($content);