我尝试搜索和替换字符串内的数组元素,但不知道如何做到这一点!我的代码示例:
$string_text = 'some random text with random lenght ';
function check_strings($string_text){
$new_string_text = $string_text; //random text with randon lenght
$array_of_3000 = ['some','text','hello','no','why','oh','random']; // array with lenght of 3000
$text_tokens = explode($new_string_text,' '); // to make it array
foreach($text_tokens as $token_index =>$token ){ // loop on $text_tokens
if (in_array($token, $array_of_3000)){ // if token in $array_of_3000 -> change token with link
$token_link = sprintf("<a href='<?php echo site_url('/%s'); ?>' > %s </a>",$tokens,$tokens); // changeing $token to html link
// update $new_string_text , $token with -> $token_link
$new_string_text = str_replace($tokens,$token_link,$tokens);
}
}
return $new_string_text;
}
// text = 'some random text with random lenght ' -> same , text , random x2 are in $array_of_3000 so need to change them with html link
// random x2 -> if find more as 1 just link 1 of them
// " <a href='<?php echo site_url('/some'); ?>' > some </a>"
// " <a href='<?php echo site_url('/text '); ?>' > text </a>"
// " <a href='<?php echo site_url('/random '); ?>' > random </a>"
// output -> all words in input string if can finded in $array_of_3000 need change with it link
if语句(in_array())不工作,我不知道如何找到匹配的词我该怎么做呢?谢谢你的帮助:)
谢谢每一个我修复它代码现在运行正常了' ' '
if (in_array($token, $array_of_words)){ // if token in $array_of_3000 -> change token with link
$token_link = sprintf("<a href='<?php echo site_url('/%s'); ?>' > %s </a>",$tokens,$tokens); // changeing $token to html link
// update $new_string_text , $token with -> $token_link
$new_string_text = str_replace($tokens,$token_link,$tokens);
}
}
您可以使用php str_replace (php manual)函数
str_replace
的例子:
$str= 'random text idk';
$tokens = ['random', 'idk'];
$newTokens = ['token1', 'token2'];
$str = str_replace($tokens, $newTokens, $str));
// value of str: "token1 text token2"
对于您的示例,您可以使用
function check_strings($string_text){
$array_of_3000 = ['some', 'text', 'hello', 'no', 'why', 'oh', 'random'];
$array_of_3000_replacements = [];
foreach ($array_of_3000 as $oldToken) {
$array_of_3000_replacements[] = sprintf("<a href='<?php echo site_url('/%s'); ?>' > %s </a>", $oldToken, $oldToken);
}
return str_replace($array_of_3000, $array_of_3000_replacements, $string_text);
}