如何将字符串中用“-”包裹的图片文件名还原为完整img标签?
Got it, let's reverse the process you did earlier and turn those hyphen-wrapped image filenames back into full, properly formatted img tags. Here are two straightforward approaches to achieve this:
方法1:数组遍历处理(直观易理解)
This method breaks down the processed string into parts, checks each part to see if it's an image filename, and reconstructs the original HTML step by step.
// Your processed output string $processedStr = "-1f602.png-checking-1f601.png-1f62c.png-working check-1f600.png-"; // Base URL for all emoji images (matches the path from your original code) $imgBaseUrl = "http://localhost/sng/assets/js/plugins/em/2.1.4/assets/png/"; // Split the string by "-" and filter out empty values (from leading/trailing hyphens) $parts = explode('-', $processedStr); $parts = array_filter($parts); $originalHtml = ''; foreach ($parts as $part) { // Check if the part is an image filename (ends with .png) if (str_ends_with($part, '.png')) { // Reconstruct the full img tag with original class and src $originalHtml .= '<img class="emojioneemoji" src="' . $imgBaseUrl . $part . '">'; } else { // It's plain text, add it directly $originalHtml .= $part; } } // Output the restored HTML echo $originalHtml;
方法2:正则表达式替换(简洁高效)
If you prefer a more concise solution, regex can match and replace the hyphen-wrapped image filenames in one go:
$processedStr = "-1f602.png-checking-1f601.png-1f62c.png-working check-1f600.png-"; $imgBaseUrl = "http://localhost/sng/assets/js/plugins/em/2.1.4/assets/png/"; // Regex pattern to match hyphen-wrapped .png filenames (hex-based, matching your emoji filenames) $originalHtml = preg_replace( '/-([a-f0-9]+\.png)-/', '<img class="emojioneemoji" src="' . $imgBaseUrl . '$1">', $processedStr ); // Remove any remaining leading hyphen (from the start of the original processed string) $originalHtml = ltrim($originalHtml, '-'); echo $originalHtml;
说明
Both methods will output the exact original HTML string you started with:
<img class="emojioneemoji" src="http://localhost/sng/assets/js/plugins/em/2.1.4/assets/png/1f602.png">checking<img class="emojioneemoji" src="http://localhost/sng/assets/js/plugins/em/2.1.4/assets/png/1f601.png"><img class="emojioneemoji" src="http://localhost/sng/assets/js/plugins/em/2.1.4/assets/png/1f62c.png">working check<img class="emojioneemoji" src="http://localhost/sng/assets/js/plugins/em/2.1.4/assets/png/1f600.png">
The key here is using the consistent base URL from your original code to rebuild the src attribute for each image. If your emoji path ever changes, just update the $imgBaseUrl variable and both methods will still work.
内容的提问来源于stack exchange,提问作者abbas

