1

I need a combination of if statements in which a specific word is occurring twice, then only the first one of these instances needs to be removed.

In my code $heading_title is a string to display as a product name. Now in two cases the heading title uses the same word twice.

heading title = Same Same words used

or

heading title = Words Words are the same

or

heading title = correct words used

Now in the case of Same and Words I want the string to be trimmed so it will display like:

Same words used and Words are the same

the last heading title is ok. Is there a way to accomplish that?

I tried some answers about trim here on Stack, but I cannot get it to work, so only the initial code is pasted.

<h1 class="heading-title" itemprop="name"><?php echo $heading_title; ?></h1>

Result is that for most products it is ok, but in those two cases where the first word is the same, it doesn't look nice for a product name..

Stefanl
  • 45
  • 5

1 Answers1

1

I would suggest to solve this using regex. What I got from your question, you would like to remove duplicate words from the start of the string. A pattern like this would help:

^(\w+)\s(\1)(?=\s)

Regex Demo

Code Sample:

$re = '/^(\w+)\s(\1)(?=\s)/m';
$str = 'Words Words are the same
correct words used
Same words used and Words are the same
Same words used and Words are the same Same';
$subst = '$1';

$result = preg_replace($re, $subst, $str);
echo $result;
wp78de
  • 18,207
  • 7
  • 43
  • 71
  • Thanks, this helped as a constructive answer, i couldn't get around with the "suggested answers", you clarified it with exactly my problem. Now my problem is solved. – Stefanl Feb 08 '19 at 12:26