检查并替换字符串PHP中的double表达式

时间:2018-10-23 18:06:22

标签: php regex preg-replace

这是我的字符串,例如:

$x = " i love you/i love her/you love me/you love me "

我想在每个空白处都放-因此我使用:

$y = preg_replace(" ","-",$x);

我得到:

  $y = " i-love-you/i-love-her/you-love-me/you-love-me "

在这个字符串中,我有两倍的表达爱你,在这种情况下,当我拥有它时,我想添加另一个而不是-,我想添加2-

所以我的最终字符串将如下所示:

$y = " i-love-you/i-love-her/you-love-me/you--love--me "

您能帮我这些吗,因为如果我使用preg replace,它将对整个字符串产生影响?

5 个答案:

答案 0 :(得分:1)

您可以通过 regex non-regex 两种方式来做到这一点,但这是我在array_count_values()和{{1 }}。希望它能帮助您:)

str_replace()

输出:

<?php
$x = " i love you/i love her/you love me/you love me ";
$sentence = explode('/',trim($x));

$value_counts = array_count_values($sentence);
$expected_result = [];
foreach($value_counts as $k=>$v){
    if($v<2){
        $expected_result[] = str_replace(' ','-',$k);
    }else{
        $expected_result[] = str_replace(' ','-',$k);
        for($i=2;$i<=$v;$i++){
            $expected_result[] = str_replace(' ','--',$k); 
        }
    }
}

echo " ".implode('/', $expected_result)." ";

演示: https://3v4l.org/Hh6Pj

答案 1 :(得分:1)

尝试这个简单的代码

$x = "i love you/i love her/you love me/you love me";
$strArr = explode("/",$x);
$temp = array();
foreach($strArr as $value){
    if(in_array($value,$temp)){
       $result[]=str_replace(" ","--",$value);    
    }else{
       $result[]=str_replace(" ","-",$value);
    }
    $temp[] = $value;
}
echo implode("/",$result);

答案 2 :(得分:0)

另一种更为冗长且可能更慢的方法:{

function format_string($x)  
{
    //trim whitespace to avoid "-" at beginning and end 
    $x = str_replace(" ","-",trim($x));
    // create an array of each entry 
    $entries = explode("/", $x);
    //count each entry 
    $entry_counts = array_count_values($entries);

    foreach($entry_counts as $string => $count){
        if($count == 2){
            $needs_updating = $string;  
        }
    }

    if(isset($needs_updating)){
        foreach($entries as $index => &$entry){
            if($entry == $needs_updating){
                $entries[$index] = str_replace("-", "--",$entry);
            }
        }

        return implode("/", $entries); 
     }

    return implode("/", $entries); 

}

答案 3 :(得分:0)

从原始字符串开始,您可以匹配用斜杠分隔的短语,并在回调函数中进行空格替换,该回调函数可跟踪短语的使用情况。如果其中一个短语已经出现,请用双破折号代替单个破折号。

library(lattice)
library(latticeExtra)
library(grid)

## Sample data
x <- seq(1:10)
y <- x^2
y2 <- x*2

## Prepare list of scales setting that suppresses ticks on top axis
myScales <- list(x = list(tck = c(1,0)))

## Prepare parameter settings, including setting the color used in
## plotting axis line to "transparent"
myTheme <- simpleTheme(col = c("black", "red"),
                       lty = c(1,1))
myTheme <- c(myTheme, list(axis.line = list(col = "transparent")))

## Write a custom axis function that only plots axis lines on the
## left, right, and bottom sides
myAxisFun <- function(side, line.col, ...) {
    if (side == "left") {
        grid.lines(x = c(0, 0), y = c(0, 1),
                   default.units = "npc")
    } else if (side == "right") {
        grid.lines(x = c(1, 1), y = c(0, 1),
                   default.units = "npc")
    } else if (side == "bottom") {
        grid.lines(x = c(0, 1), y = c(0, 0),
                   default.units = "npc")
    }
    axis.default(side = side, line.col = "black", ...)
}


## Construct two component plots
plot1 <- xyplot(y ~ x, col="black", type = "l",
                ylab = "Label1", xlab = "",
                par.settings = myTheme,
                scales = myScales,
                axis = myAxisFun) 
plot2 <- xyplot(y2 ~ x, col="red", type = "l",
                ylab = "Label2", xlab = "",
                par.settings = myTheme,
                scales = myScales,
                axis = myAxisFun)

## Meld the two plots 
doubleYScale(plot1, plot2, add.ylab2 = TRUE)

答案 4 :(得分:0)

这是我要去的地方

$x = " i love you/i love her/you love me/you love me ";

$x = preg_replace_callback('/([^\/]+)\/(\1)?/', function($match){
    if(isset($match[2])){
        return str_replace(' ', '-', trim($match[1])).'/'.str_replace(' ', '--', trim($match[2]));
    }else{
        return str_replace(' ', '-', trim($match[1])).'/';
    }
}, $x);

echo $x;

输出

i-love-you/i-love-her/you-love-me/you--love--me 

以及它的缩小版本:

$x = " i love you/i love her/you love me/you love me ";
echo preg_replace_callback('/([^\/]+)\/(\1)?/',function($m){return isset($m[2])?str_replace(' ','-',trim($m[1])).'/'.str_replace(' ','--',trim($m[2])):str_replace(' ','-',trim($m[1])).'/';},$x);