簡體   English   中英

如何在php的數組中檢查單詞是否以'x'開頭

[英]How to check if a word begins with 'x' in an array in php

前景:我有一個我正在處理的項目,它使用存儲在數據庫中的電子郵件模板,每個電子郵件正文都包含模式{{$shortcode}}中的幾個短代碼。

問題:目前有一個用於更改電子郵件模板正文的管理員設置。 在編輯期間,我想向進行編輯的人添加一條提示通知,顯示允許的短代碼。

例如,您正在編輯 XYZ 模板,允許的短代碼是 {{$shortcode1}}、{{$shortcode2}} 和 {{$shortcode3}}

我想做的事:該網站有幾個帶有不同短代碼的電子郵件模板,並且模板一旦添加就很容易被更改或新的。

為了避免進入每個模板並列出它擁有的每個簡碼,在控制器中,我想檢查模板中的簡碼,提取它們並將它們傳遞到視圖中。

例如

$message = 'Hello {{$first_name}}, you have requested to change your password, your reset link is {{$link}}';

$shortcodes = explode(' ', $message);

如果我dd($shortcodes) ,我得到這個數組

0 => "Hello"
  1 => "{{$first_name}},"
  2 => "you"
  3 => "have"
  4 => "requested"
  5 => "to"
  6 => "change"
  7 => "your"
  8 => "password,"
  9 => "your"
  10 => "reset"
  11 => "link"
  12 => "is"
  13 => "{{$link}}"

現在我想在上面的數組中獲取所有以{{$開頭的單詞,這可能嗎?

也許你應該在這里使用正則表達式,像這樣:

$message = 'Hello {{$first_name}}, you have requested to change your password, your reset link is {{$link}}';
        
preg_match_all('/{{\$\w+}}/', $message, $matches);
        
dd($matches[0]);

/*
[
  0 => "{{$first_name}}"
  1 => "{{$link}}"
]
*/

您可以使用array_filter

$result = array_filter($words, fn($word) => strpos($word, '{{$') === 0);

但也許在電子郵件模板的文本上使用正則表達式會是一個更干凈的解決方案(例如使用preg_match_allhttps://www.php.net/manual/en/function.preg-match-all.php

$message = 'Hello {{$first_name}}, you have requested to change your password, your reset link is {{$link}}';

$shortcodes = explode(' ', $message);

foreach($shortcodes as $sc){
    if( ($sc[0] == "{") && ($sc[1] == "{")  && ($sc[2] == "$") ){
        echo $sc;   
    }
}

為什么沒有人使用為此而設計的功能?

foreach($shortcodes as $word){
    if(str_starts_with($word, 'x')){
        ## CODE TO BE EXECUTED
    }
}

請使用此腳本:

<?php
function getShortCodes($string, $start, $end){
    $count = substr_count($string, $start);
    if ($count == 0) return [];
    $matchings = [];
    for($i = 0; $i <= $count; $i++){
        $string = ' ' . $string;
        $ini = strpos($string, $start);
        if ($ini == 0) continue;
        $ini += strlen($start);
        $len = strpos($string, $end, $ini) - $ini;
        $subStr = substr($string, $ini, $len);
        $matchings[] = $subStr;
        $string = str_replace('{{$'.$subStr.'}}',"",$string);
        
    }
    return $matchings;
}

$message = 'Hello {{$first_name}}, you have requested to change your password, your reset link is {{$link}}';

$parsed = getShortCodes($message, '{{$', '}}');

print_r($parsed);

一個更簡單的解決方案是使用preg_match_all()

$message = 'Hello {{$first_name}}, you have requested to change your password, your reset link is {{$link}}';
preg_match_all('/{{[^{]*}}/', $message, $matches);
var_dump($matches);
//array(1) {
//  [0]=>
//  array(2) {
//    [0]=>
//    string(15) "{{$first_name}}"
//    [1]=>
//    string(9) "{{$link}}"
//  }
//}

這是一個jist

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM