PHP에서 워드프레스 숏코드 스타일 함수를 만드는 방법
저는 "[133]"과 같은 숏코드를 이미지로 대체하기 위해 PHP에 워드프레스 숏코드 스타일의 기능을 만들려고 합니다.기본적으로 저는 이미지 URL/제목/부제목의 MySQL 표를 가지고 있고, 다음과 같이 짧은 코드로 페이지의 텍스트에 동적으로 삽입할 수 있기를 원합니다.
허풍.[5] 또한, 가식적인 가식적인 가식적인 가식적인 가식적인 가식적인 가식적인 가식적인 가식적인 [27]야, 그리고 허튼소리![[129]]
따라서 ID를 $id로 잡은 다음 mysql_query("SELECT title, subtitle, url FROM images = $id")와 같은 MySQL 쿼리에 입력한 다음 "[id]"를 img/title/subtitle로 대체합니다.같은 페이지에서 여러 번 할 수 있으면 좋겠습니다.
저는 이것이 regex와 preg_match, preg_replace, strstr, strpos, substr의 조합을 포함해야 한다는 것을 압니다.하지만 어디서부터 시작해야 할지, 어떤 기능을 사용해야 어떤 일을 해야 할지 잘 모르겠습니다.전략을 추천해 주실 수 있습니까?코드 자체는 필요 없습니다. 어떤 부품에 무엇을 사용해야 할지만 알면 매우 도움이 될 것입니다.
다음과 같은 짧은 코드를 작성할 수 있는 경우:
[[function_name_suffix parameter1 parameter2 ...]]
여기에 더 완전한 방법이 있습니다.preg_replace_callback
그리고.call_user_func_array
파라미터화된 쇼트 코드를 구현합니다.
function shortcodify($string){
return preg_replace_callback('#\[\[(.*?)\]\]#', function ($matches) {
$whitespace_explode = explode(" ", $matches[1]);
$fnName = 'shortcode_'.array_shift($whitespace_explode);
return function_exists($fnName) ? call_user_func_array($fnName,$whitespace_explode) : $matches[0];
}, $string);
}
이 함수가 정의된 경우:
function shortcode_name($firstname="",$lastname=""){
return "<span class='firstname'>".$firstname."</span> <span class='lastname'>".$lastname."</span>";
}
그럼 이 전화는
print shortcodify("My name is [[name armel larcier]]");
출력 의지:
My name is <span class='firstname'>armel</span> <span class='lastname'>larcier</span>
이것은 단지 제가 supertrue의 아이디어를 바탕으로 실행한 것입니다.
어떤 피드백이라도 환영합니다.
기능이 있는getimage($id)
MySQL 쿼리를 수행하고 대체 텍스트를 포맷하면 필요한 모든 작업을 수행할 수 있습니다.
$text = "Blabla [[5]] and [[111]] bla bla bla [[27]] and bla bla bla! [[129]]";
$zpreg = preg_match_all('#\[\[(\d{1,3})\]\]#', $text, $matches );
var_dump( $matches[1] );
$newtext = preg_replace('#\[\[(\d{1,3})\]\]#', getimage($matches[1][?????]), $text);
echo $newtext;
뭐를 넣어야 할지 생각만 하면 돼요getimage()
(어디??????????????????????????????????????????????????????????????????????????[[id]]
.
자세한 사항은 공식 문서를 참조하여 확인하시기 바랍니다.
이를 위해 다양한 방법을 사용할 수 있으며, 이는 당신이 어떻게 표시할 것인가에 따라,
"Hello [34] world" 문장을 들어보세요.
간단한 함수 만들기(예: replaceCode($string)
function replaceCode($string){
$pos = strpos($string, '['); // Find the first occurrence of the bracket
if($pos != false){
// If everything is ok take the next 2 numbers from it
// Check for a close bracket & remove ]
// call another function to replace the number with the image text
}
}
괄호가 더 발견되면 함수를 재귀적으로 호출하고 나머지 문자열을 함수에 다시 전달합니다.
참고: [ 및 ] 가 적절하게 균형을 이루는지 확인하려면 먼저 검증을 수행해야 할 수도 있습니다!
<?php
function get_profile_image($image_url){
return "<img src='{$image_url}' height='200px' width='200px' />";
}
$trans = array(
"[[1]]" => "Vishal",
"[[2]]" => "Kumar",
"[[3]]" => "Sahu",
"[[4]]" => "Web Designer",
"[[5]]" => "Draw and Paint",
"[[6]]" => ucwords("any programming language"),
"[[7]]" => strtoupper("PHP, JAVASCRIPT and HTML"),
"[[8]]" => get_profile_image("http://php.net/images/logos/php-logo.svg"),
"[[9]]" => "http://php.net/images/logos/php-logo.svg"
);
$str = <<<HEREDOC_1
[[8]]
<pre>My name is [[1]] [[2]] [[3]].
I am a [[4]] and I love to [[5]].
I don't know [[6]] but I know [[7]] little bit.</pre>
Here is my profile image <img src='[[9]]' alt='[[1]]-[[2]]-[[3]]-[[4]]' />
HEREDOC_1;
echo strtr($str, $trans);
산출량은.
[http://php.net/images/logos/php-logo.svg ] 제 이름은 Vishal Kumar Sahu입니다.저는 웹디자이너이고 그림그리기를 좋아합니다.나는 Any Programming Language를 모르지만 PHP, JAVASCRIPT, HTML을 조금 알고 있습니다.프로필 이미지 [Vishal-Kumar-Sahu-Web Designer] 입니다.
5.6에서는 잘 작동하고 있습니다.
제 생각에 정규군은 다음과 같습니다.
/\[\[[1-9]{1,3}\]\]/g
(이중괄호 안에 1~3자리 숫자가 있는 경우)
언급URL : https://stackoverflow.com/questions/4568463/how-to-create-a-wordpress-shortcode-style-function-in-php
'prosource' 카테고리의 다른 글
데이터베이스 정상 양식이란 무엇이며 예를 들어 줄 수 있습니까? (0) | 2023.10.05 |
---|---|
Angular 5는 일부 클래스에서 'ng-star-inserted'를 추가합니다. - 그게 뭐죠? (0) | 2023.10.05 |
특정 양식을 제출한 후 여러 양식에서 결합된 입력 데이터를 타사로 전송하는 Gravity Forms (0) | 2023.10.05 |
자바스크립트에서 Array.any?와 동등한 것은 무엇입니까? (0) | 2023.10.05 |
.NET 웹 API 2 OWIN 베어러 토큰 인증 (0) | 2023.10.05 |