Tôi cũng cần chức năng này trong khuôn khổ PHP của mình. Đây là những gì tôi đã viết, nó hoạt động khá tốt. Nó hoạt động với các hàm ẩn danh mà tôi thực sự thích (nó giống như các hàm gọi lại trong JavaScript).
<?php
//The content which should be parsed
$content = '<p>Hello, my name is John an my age is [calc-age day="4" month="10" year="1991"].</p>';
$content .= '<p>Hello, my name is Carol an my age is [calc-age day="26" month="11" year="1996"].</p>';
//The array with all the shortcode handlers. This is just a regular associative array with anonymous functions as values. A very cool new feature in PHP, just like callbacks in JavaScript or delegates in C#.
$shortcodes = array(
"calc-age" => function($data){
$content = "";
//Calculate the age
if(isset($data["day"], $data["month"], $data["year"])){
$age = date("Y") - $data["year"];
if(date("m") < $data["month"]){
$age--;
}
if(date("m") == $data["month"] && date("d") < $data["day"]){
$age--;
}
$content = $age;
}
return $content;
}
);
//http://stackoverflow.com/questions/18196159/regex-extract-variables-from-shortcode
function handleShortcodes($content, $shortcodes){
//Loop through all shortcodes
foreach($shortcodes as $key => $function){
$dat = array();
preg_match_all("/\[".$key." (.+?)\]/", $content, $dat);
if(count($dat) > 0 && $dat[0] != array() && isset($dat[1])){
$i = 0;
$actual_string = $dat[0];
foreach($dat[1] as $temp){
$temp = explode(" ", $temp);
$params = array();
foreach ($temp as $d){
list($opt, $val) = explode("=", $d);
$params[$opt] = trim($val, '"');
}
$content = str_replace($actual_string[$i], $function($params), $content);
$i++;
}
}
}
return $content;
}
echo handleShortcodes($content, $shortcodes);
?>
Kết quả:
Xin chào, tôi tên là John một tuổi của tôi là 22.
Xin chào, tôi tên là Carol một tuổi của tôi là 17.
Vui lòng thử thư viện của tôi, đó là độc lập và đã chiến đấu thử nghiệm trong sản xuất: https://github.com/thunderer/Shortcode. Nếu bạn cần bất cứ điều gì cho tôi biết! –
@TomaszKowalczyk cảm ơn!:) – Iamzozo