为了账号安全,请及时绑定邮箱和手机立即绑定

如何在preg match php代码上调用函数

如何在preg match php代码上调用函数

PHP
郎朗坤 2022-12-23 14:02:46
我有代码..<?phpfunction word() {     $arr = array("/c/","/b/","/c/");     echo $arr[array_rand($arr)];}$text = "a";if(preg_match("$word()", $text)) {     $result = "found";}else{     $result = "not found";}echo $result;?>如何将函数调用word();到preg_match.我想随机搜索中的单词preg_match。我试过了,但没用。如何修复此代码。
查看完整描述

1 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

如果你让你的函数word()返回随机字符串而不是回显它,你可以通过调用函数将它用作任何值。


function word() {

    $arr = array("/c/","/b/","/c/");

    return $arr[array_rand($arr)];

}


if( preg_match(word(), $text) ) {

    $result = "found";

}

else {

    $result = "not found";

}


echo $result;

如果它更清楚,这与将函数的结果存储在变量中并使用它相同。


这些都是一样的:


// Writing the pattern in place.

preg_match("/a/", $text);


// Storing it in a variable before use.

$to_match = "/a/";

preg_match($to_match, $text);


// Storing it in a variable where the value is returned from a function.

$to_match = word();

preg_match($to_match, $text);


// Using a function directly in the call to `preg_match`.

preg_match(word(), $text);


查看完整回答
反对 回复 2022-12-23
  • 1 回答
  • 0 关注
  • 194 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号