check and replace double expression in string PHP

php string replace regex
php str_replace multiple
preg_replace special characters
replace first character in string php
php replace string in file
preg_replace not working
remove specific characters from string php
php replace special characters

This is my string for example:

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

and i wanted in every blank space to put - so i use:

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

and i get:

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

in this string i have double expresion YOU LOVE ME, in that case when i have that, i want to add in other not one -, i want to add 2 --

so my final string will look like:

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

Can you help me with these, cause if i use preg replace it will have influence on whole string?

Try This simple code

$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);

str_replace — Replace all occurrences of the search string with the replacement string An array may be used to designate multiple replacements. a portion of a string; preg_replace() - Perform a regular expression search and replace  See regular expression to replace two (or more) consecutive characters by only one? By the way: you should use the preg_* (PCRE) functions instead of the deprecated ereg_* functions (POSIX). Richard Szalay 's answer leads the right way:

You can to do it by both ways like regex or non-regex way but this what I got in my mind with array_count_values() and str_replace(). Hope it'll help you :)

<?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)." ";

Output:

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

DEMO: https://3v4l.org/Hh6Pj

preg_replace — Perform a regular expression search and replace Make sure you are aware of PHP's string syntax to know exactly how the interpreted To replace double whitespace by a single space character in a sentence you need to  Parameters. If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject.If replace has fewer values than search, then an empty string is used for the rest of replacement values.

Another more verbose and likely slower method :{

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); 

}

Example #2 Using substr_replace() to replace multiple strings at once str_replace() - Replace all occurrences of the search string with the replacement I started with a regular expression solution, but found that I kept matching the wrong  Regular expressions are a very useful tool for developers. They allow to find, identify or replace a word, character or any kind of string. This tutorial will teach you how to master PHP regexp and show you extremely useful, ready-to-use PHP regular expressions that any web developer should have in his toolkit.

Starting with the original string, you can match the slash separated phrases and do the space replacement in a callback function that keeps track of phrases as it goes. If one of the phrases has already appeared, replace the spaces with double dashes instead of single.

$pattern = '/(?<=^|\/).+?(?=\/|$)/';
$phrases = [];
$y = preg_replace_callback($pattern, function($phrase) use (&$phrases) {
    $separator = in_array($phrase[0], $phrases) ? '--' : '-';
    $phrases[] = $phrase[0];
    return str_replace(' ', $separator, $phrase[0]);
}, trim($x));

If search is an array and replace is a string, then this replacement string is used for it might replace a previously inserted value when doing multiple replacements. string; preg_replace() - Perform a regular expression search and replace  Regular expressions are powerful pattern matching algorithm that can be performed in a single expression.Regular expressions use arithmetic operators such as (+,-,^) to create complex expressions. PHP Regular Expressions Tutorial: Preg_match, Preg_split, Preg_replace

Here is my go:

$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;

Output

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

And the smallified version of it:

$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);

preg_replace_callback — Perform a regular expression search and replace using a callback The callback should return the replacement string. This is the​  When preg_replace() is called with the /e modifier, the interpreter must parse the replacement string into PHP code once for every replacement made, while preg_replace_callback() uses a function that only needs to be parsed once.

5, PHP 7). mb_ereg_replace — Replace regular expression with multibyte support replacement. The replacement text. string. The string being checked. Was just updating code to replace ereg() with strpos() and preg_match and the thought occured that preg_match() could be optimized to quit early when only searching if a string begins with something, for example

This function scans string for matches to pattern , then replaces the matched text with string; preg_replace() - Perform a regular expression search and replace It's worth mentioning for ultimate clarity that you're safest using double quotes  preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

preg_replace — Perform a regular expression search and replace To use backslash in replacement, it must be doubled ("\\\\" PHP string). arise from backreference usage with either single or double quotes (e.g. 'strlen(\'$1\')+strlen(​"$2")'). Parameters. string. The input string. An array of string s can be provided, in which case the replacements will occur on each string in turn. In this case, the replacement, start and length parameters may be provided either as scalar values to be applied to each input string in turn, or as array s, in which case the corresponding array element will be used for each input string.

Comments
  • so you want to add -- in the last one always
  • Given ` I love you/you love me/I love you/you love her/you love me/she loves me`, what do you expect
  • @AlivetoDie yes, not always, only if tha last one is duplicate of previous one
  • You could use a capture group quantifier to look for duplicates that are next to each other like /\/([^\/]+)\/(\1)/ then do some additional replacements based on capture group 2
  • This code is great, i wanted to use it for another string like this: $x = "cellular & data radios|modems|analog modems|analog--modems|analog--modems" In this case i have triple double expression, what to change in code, to only the last one have --?
  • Add below code inside the in_array condition $tmp = array_count_values($temp); if($tmp[$value]>1) $result[]=str_replace(" ","---",$value); else $result[]=str_replace(" ","--",$value);
  • No you didnt understand me very well, if i have triple case, then i want only to add two lines -- in the last one, and it the first two only one line - like this: $x = "cellular & data radios|modems|analog-modems|analog-modems|analog--modems"
  • Try this inside the in_array()condition $key = array_search($value,array_reverse($temp,true)); if(!empty($key)) $result[$key] = str_replace(" ","-",$value); $result[]=str_replace(" ","--",$value);
  • Dude you are awsome! Thank you very much!