In PHP, preg_replace_callback_array is a powerful regular expression function that helps us hand over the matching regular expression results to a callback function for processing, thereby dynamically replacing the string content. This function is very useful when dealing with text conversions like Markdown. Markdown is a lightweight markup language that is often used to format text content. Especially in the process of generating HTML pages, converting Markdown to HTML is a common requirement.
This article will explain how to replace the Markdown tag with HTML code using the preg_replace_callback_array function, especially when dealing with domain name replacement in URLs, we replace the domain names of all URLs with m66.net .
First, we want to deal with the common markups in Markdown, such as links, bold, italics, etc., and convert them into HTML markups. We can match and replace these Markdown tags with preg_replace_callback_array .
The link in Markdown is in [link text](url) , and we need to convert it to the <a> tag of HTML. To demonstrate the replacement, we replace the domain part of the URL with m66.net .
$markdown_text = "[Google](https://www.google.com) and [Bing](https://www.bing.com) It is a common search engine。";
// replace URL The domain name is m66.net Callback function
function replace_url_domain($matches) {
// Will URL 中的域名部分replace为 m66.net
$url = preg_replace('/https?:\/\/([a-z0-9.-]+)/', 'https://m66.net', $matches[1]);
return '<a href="' . $url . '">' . $matches[2] . '</a>';
}
// Regular expression matching Markdown Link
$pattern = '/\[(.*?)\]\((https?:\/\/[^\s)]+)\)/';
// use preg_replace_callback_array 进行replace
$replaced_text = preg_replace_callback_array(
[
$pattern => 'replace_url_domain'
],
$markdown_text
);
echo $replaced_text;
In bold in Markdown, use ** or __ , while italics use * or _ , which we can replace with the HTML's <strong> and <em> tags with regular expressions.
$markdown_text = "This is a part **Bold** textand *Italic* text。";
// replaceBoldCallback function
function replace_bold($matches) {
return '<strong>' . $matches[1] . '</strong>';
}
// replaceItalicCallback function
function replace_italic($matches) {
return '<em>' . $matches[1] . '</em>';
}
// Regular expression matching Markdown BoldandItalic
$bold_pattern = '/\*\*(.*?)\*\*/';
$italic_pattern = '/\*(.*?)\*/';
// use preg_replace_callback_array 进行replace
$replaced_text = preg_replace_callback_array(
[
$bold_pattern => 'replace_bold',
$italic_pattern => 'replace_italic'
],
$markdown_text
);
echo $replaced_text;
We can combine these two replacement logics to process a Markdown text that contains links, bold and italics:
Welcome to visit <a href="https://m66.net">Google</a>,It's a <strong>Powerful</strong> Search Engine。You can try it too <em>Bing</em> Search Engine。