Cruglk
Cruglk

Reputation: 37

Placing a dash for each identical word (regex, php)

Please tell me if it is possible to make a search for all identical words through rejax and insert a dash between them until such a word is no longer the next in the sentence.

Example here: https://regex101.com/r/1GQiQ8/2

My regex:

(\blong\b|\banyword\b)(-| )(\blong\b|\banyword\b)

Sample text:

test text long long test text
test text long long long long long long test text
test text long long test test long long long test text

How it should be:

test text long-long-long-long-long-long test text
test text long-long test test long-long-long test text

How does it work now:

test text long-long test text
test text long-long long-long long-long test text
test text long-long test test long-long long test text

Upvotes: 2

Views: 41

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

Simple foreach() loop will do the job as well:

<?php

$string = 'test text long long test text';

$array = explode(' ',$string);

$finalString = '';
foreach($array as $key=> $arr){
    if($key ==0){
        $finalString = $arr;
    }else{
        if($arr == $array[$key-1]){
            $finalString .='-'.$arr;
        }else{
             $finalString .=' '.$arr;
        }
        
    }
    
}
echo $finalString;

Output:https://3v4l.org/FVSRU And https://3v4l.org/jso3U

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

You can use

\b(long|anyword)\b\K[- ](?=(?:(?1))\b)

Replace with -. See the regex demo.

If the words must be identical use \1 instead of (?1):

\b(long|anyword)\b\K[- ](?=\1\b)

See this regex demo

Details

  • \b(long|anyword)\b - Group 1: either of two words, as a whole word
  • \K - match reset operator, it removes all text matched so far from the match memory buffer
  • [- ] - either a hyphen or space
  • (?=(?:(?1))\b) - a positive lookahead that matches a location immediately followed with a whole long or anyword word.
  • (?=\1\b) - a positive lookahead that matches a location immediately followed with the string captured in Group 1 as a whole word.

Upvotes: 1

Related Questions