简体   繁体   English

使用正则表达式替换句子中的字符串

[英]Replacing string from sentence using Regex expressions

I want to make a script that finds strings with this format {Hello|Hi|Hey} from different sentences using {([\\w|]+)} and then uses (?<=[{|])\\w+(?=[|}]) to get the individual words and randomly selects one of the words and replaces the starting with it.我想制作一个脚本,使用{([\\w|]+)}从不同的句子中查找这种格式的字符串{Hello|Hi|Hey}然后使用(?<=[{|])\\w+(?=[|}])获取单个单词并随机选择其中一个单词并用它替换开头。

Do I have to use a loop to find each formatted string and then put the individual words in an array and count values in the array and use rand function to get random value and replace the string with it?我是否必须使用循环来查找每个格式化的字符串,然后将单个单词放入数组中并计算数组中的值,并使用 rand 函数获取随机值并用它替换字符串? Which functions do I have to use?我必须使用哪些功能?

You dont need twice preg_match;你不需要两次 preg_match;

this is maybe what you are asking:这也许是你要问的:

<?php

$a = '{Hello|Hi|Hey}';

preg_match ( '{([\w|]+)}',$a,$array );

$items = explode("|",  $array[0]);
echo $items[rand(0, count($items) - 1)]  ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM