如何使用PHP实现删除首个<br>前及末个<br>后的内容?
<br/> and After Last <br/> Got it, let's work through this string manipulation problem you're facing. You need to strip everything before the first <br/> and everything after the last <br/> from your original string—here are a couple of reliable, easy-to-implement approaches in PHP:
Method 1: Using explode() and Array Manipulation (Simple & Straightforward)
This approach is great if your string structure is consistent (you know there are at least two <br/> separators). It breaks the string into an array, removes the unwanted first and last elements, then joins the rest back together:
$originalString = "Aaron Wind<br/>45 Civic Drive<br/>Greensborough VIC 3088<br/>Australia<br/>0450111222"; // Split the string into an array using <br/> as the delimiter $stringParts = explode('<br/>', $originalString); // Remove the first element (content before the first <br/>) array_shift($stringParts); // Remove the last element (content after the last <br/>) array_pop($stringParts); // Join the remaining parts back with <br/> $trimmedString = implode('<br/>', $stringParts); echo $trimmedString; // Output: 45 Civic Drive<br/>Greensborough VIC 3088<br/>Australia
Bonus: Add Robustness for Edge Cases
If there's a chance your input might have fewer than two <br/> tags (which would make the result empty or invalid), add a quick check:
if (count($stringParts) >= 3) { array_shift($stringParts); array_pop($stringParts); $trimmedString = implode('<br/>', $stringParts); } else { // Handle cases where there aren't enough separators $trimmedString = ""; // Or return original string, depending on your needs }
Method 2: Using Regular Expressions (Flexible for Variations)
If you need to handle variations of the line break tag (like <br>, <br />, or <br/>), regex is a better fit. We'll do two replacements: first strip everything up to the first line break, then strip everything after the last line break.
$originalString = "Aaron Wind<br/>45 Civic Drive<br/>Greensborough VIC 3088<br/>Australia<br/>0450111222"; // Remove all content from the start to the first line break tag (supports <br>, <br/>, <br />) $afterFirstBreak = preg_replace('/^.*?<br\s*\/?>/', '', $originalString); // Remove all content from the last line break tag to the end $trimmedString = preg_replace('/<br\s*\/?>.*$/', '', $afterFirstBreak); echo $trimmedString; // Same desired output
Regex Breakdown
^.*?<br\s*\/?>: Matches from the start of the string (^) up to the first line break tag. The.*?is non-greedy, so it stops at the first occurrence of the tag.\s*accounts for optional spaces, and\/?accounts for an optional closing slash.<br\s*\/?>.*$: Matches the last line break tag through to the end of the string ($), and replaces it with nothing.
Either method will get you exactly the output you need. The array method is easier to read and debug for simple cases, while regex offers more flexibility if your line break tags might vary.
内容的提问来源于stack exchange,提问作者Mike Zhang

