简体   繁体   中英

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.

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? Which functions do I have to use?

You dont need twice 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)]  ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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