【发布时间】:2021-12-05 07:51:07
【问题描述】:
我尝试在字符串中搜索和替换数组元素,但不知道该怎么做! 我的代码前:
$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);
}
}
【问题讨论】:
-
请提高您问题的清晰度。此外,您可以添加您想要实现的输入 -> 输出示例。我不清楚你想做什么。
-
@Gass 谢谢,我尽量让它更清楚,我有一些随机文本和 3000 个单词的数组。如果任何数组元素在文本中,请使用链接更改它们
-
给定的代码有什么不工作的地方吗?如果是,请分享有关您面临的问题的更多详细信息
-
@NicoHaase 是,如果语句不起作用。首先我需要检查字符串是否有任何数组将其更改为 html 链接
-
请通过编辑为您的问题添加所有说明。 究竟是什么不起作用?你有什么努力让它发挥作用?
标签: php arrays string if-statement replace