使用随机PHP用子字符串动态替换子字符串

时间:2018-11-16 16:19:29

标签: php regex string preg-replace

我在Dynamically Replace Substring With Substring Using PHP上找到了这个

我需要与此类似的东西,不想删除第一部分,而是随机删除两者。

这意味着,我有时需要获取子字符串的第一部分,有时需要获取最后一部分。

function deleteStringBetweenStrings($start, $end, $string) {
// create a pattern from the input and make it safe to use in a regular expression
$pattern = '|' . preg_quote($start) . '(.*)' . preg_quote($end) . '|U';
// replace every occurrence of this pattern with an empty string in full $s

tring
    return preg_replace($pattern, '', $string);
}


$String = "loads of text [[gibberish text|Text i Want]] more text  [[gibberish text|Text i Want]] more text [[if no separator then  just remove tags]]";

$String = deleteStringBetweenStrings("[[", "]]", $String);
echo $String;
//loads of text more text more text

如果我将此函数与'[['和']]'分隔符一起使用,则会删除分隔符中的完整子字符串。但我需要该字符串应包含定界符内子字符串的任何一部分(随机)。 我的预期结果将是-

结果#1 =加载大量文本乱码 其他文本我想要的文本如果没有分隔符,则只添加标签

结果#2 =大量文本我想要的文本更多的文本我想要的文本如果没有分隔符,则只需删除标签

结果#3 =大量文本我想要的文本更多文本乱码如果没有分隔符,则仅删除标签

我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

在@WiktorStribiżew的帮助下,我以这种方式对其进行了管理。它给我1个分隔符的结果,如果它有多个分隔符,则第3个部分保持不变。 如果有人帮助我获得第三部分,那就太好了。 谢谢大家。

function getSubstrings($start, $end, $string) {
    // create a pattern from the input and make it safe to use in a regular expression
    $pattern = '|' . preg_quote($start) . '(.*)' . preg_quote($end) . '|U';
    // replace every occurrence of this pattern with an empty string in full $string
    return preg_replace($pattern, '', $string);
}

function clearString($string) {
    // to remove '[]|' these, called str_replace($shortCode, $codeReplace, $string)
    $shortCode = array( "[", "]", '|');
    $codeReplace = array('', '', '');
    // initiating $StringBetweenStrings
    $StringBetweenStrings = '';
    // creates an array of [ and |
    $dl = array("[", '|');
    // randomly, calling one of the array
    $dl_before = $dl[array_rand($dl)];

    // checking if $dl_before is '[' or '|', if it's '|' then create $dl_after ']', else that would be '|'
    $dl_after =  ($dl_before=='|') ? ']' : '|';

    // split string with preg_split
    $res_array = preg_split('~(\[\[[^][|]*\|[^][]*]])~', $string, -1, PREG_SPLIT_DELIM_CAPTURE);

    foreach ($res_array as $key => $value) {
      // calling getSubstrings to get first part or last part of substring & calling str_replace to remove delimiter and separator.
      $StringBetweenStrings .= str_replace($shortCode, $codeReplace , getSubstrings($dl_before, $dl_after, $value));
    }

// return expected string
    return $StringBetweenStrings;
}