使用simple_html_dom解析表格并批量替换表格内URL后缀
Got it, let's work through this solution since you're already using Simple HTML DOM for table parsing. Adapting this to handle dynamic content (no fixed filenames needed) is totally doable—here's a clean, robust approach:
Step-by-Step Implementation
First, make sure you're loading the latest dynamic HTML content (whether it's fetched from a URL, generated dynamically, or pulled from a string). Then target only the links inside table cells to avoid modifying other parts of the page:
// Include the Simple HTML DOM library first include('simple_html_dom.php'); // Load your dynamic HTML content (replace this with your actual content source) // Example 1: Fetch from a dynamic URL $html = file_get_html('https://your-dynamic-content-url.com'); // Example 2: Load from a dynamically generated string // $html = str_get_html($yourDynamicHtmlString); // Loop through every <a> tag inside table cells foreach ($html->find('table td a') as $linkElement) { // Grab the current href value $originalHref = $linkElement->href; // Replace .htm (case-insensitive) with .php at the end of the URL // Use preg_replace to handle .HTM, .Htm, etc. $updatedHref = preg_replace('/\.htm$/i', '.php', $originalHref); // Update the href attribute in the DOM $linkElement->href = $updatedHref; } // Output the modified HTML, or save it somewhere echo $html; // Or save to a file if needed: file_put_contents('updated-content.html', $html);
Key Details for Dynamic Scenarios
- No fixed filename dependency: By loading the HTML dynamically each time (either via URL or string), you'll always process the latest content—no need to hardcode filenames.
- Precise targeting: The
table td aselector ensures you only modify links inside table cells, not other links on the page. - Case flexibility: The
iflag in the regex handles uppercase variations like.HTMor.Htm—if you know all links use lowercase.htm, you can swappreg_replacefor a simplerstr_replace('.htm', '.php', $originalHref). - Works with query parameters: The regex targets
.htmat the end of the URL, so links likepage.htm?id=123will becomepage.php?id=123correctly.
Just make sure you're reloading the HTML content each time you run this script to pick up any dynamic changes to the source.
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

