PHP中移除文本含特定后缀的域名但保留其余文本
Hey there! I get that you need to strip out specific domain suffixes from user-submitted product descriptions in PHP, leaving the rest of the text intact. Let’s break this down with a straightforward solution.
First, let's outline the core idea: we'll use a regular expression to target domains ending with your specified suffixes, then replace those matches with an empty string to remove them. Here's a reusable function that makes this easy to adjust for different suffixes.
Step 1: Reusable Removal Function
This function takes your input text and an array of target domain suffixes (like .shop, .example.com) and returns the cleaned text:
function removeSpecificDomains($text, $targetSuffixes) { // Escape special characters in suffixes to avoid regex issues $escapedSuffixes = array_map(function($suffix) { return preg_quote($suffix, '/'); }, $targetSuffixes); // Build the regex pattern: match domains ending with our target suffixes // Handles subdomains (e.g., www.xxx.shop) and is case-insensitive $suffixPattern = implode('|', $escapedSuffixes); $pattern = '/\b(?:https?:\/\/)?(?:[a-zA-Z0-9_-]+\.)+' . $suffixPattern . '\b/i'; // Replace matched domains with empty string to remove them return preg_replace($pattern, '', $text); }
Step 2: How to Use It
Let's test this with a sample product description. Suppose you want to remove all domains ending with .shop and .store:
// Original user-submitted text $productDescription = "Check out our premium laptop at www.techgear.shop — it’s cheaper than the one from gadgethub.store! This device has 16GB RAM and a 2TB SSD."; // List of domain suffixes to remove $badSuffixes = ['.shop', '.store']; // Get cleaned text $cleanedText = removeSpecificDomains($productDescription, $badSuffixes); // Output the result echo $cleanedText;
Result:
Check out our premium laptop at — it’s cheaper than the one from ! This device has 16GB RAM and a 2TB SSD.
Key Notes
- Handles HTTP/HTTPS links: The
(?:https?:\/\/)?part ensures we catch both bare domains (e.g.,techgear.shop) and full URLs (e.g.,https://www.techgear.shop). - Case-insensitive: The
imodifier means.SHOPor.Storewill also be matched and removed. - Avoids partial matches: The
\b(word boundary) prevents accidental removal of text that contains your suffix as part of a longer word (e.g., it won’t touchshopify.comif your target is.shop). - Easily adjustable: Just add or remove entries from the
$badSuffixesarray to target different domain endings (e.g.,.example.com,.co.uk).
If you need to tweak the regex for edge cases (like domains with unusual characters), feel free to adjust the character set in the pattern!
内容的提问来源于stack exchange,提问作者lonerunner

