0

I want to replace words matching words in my array in my string (long text)

This is how my array looks:

array(
 0 => "hello",
 1 => "author",
 2 => "cars",
)

This is how my string looks:

Lorem ipsum dolor sit amet, cons etetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos e t accusam et jus to duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata s anctus est Lorem ipsum dolor hello sit amet. Lorem ipsum dolor sit a met, consetetur sadip scing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed di am voluptua. carsAt vero eos et accusam et justo duo dolores et ea rebum. Stet clita author, kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

This should happen Every match (name it MATCH) should be replaced like this:

<a alt="MATCH" href="/link/MATCH">MATCH</a>

I tried to solve this problem for hours, but I just don't know how to come up with a solution ...

The word should also be replaced, if there is no space after it.

6
  • 5
    I tried to solve this problem for hours And in all these hours I hope you wrote some code which you can show us?! Commented Aug 12, 2015 at 15:53
  • 1
    php.net/str_replace php.net/preg_match Commented Aug 12, 2015 at 15:55
  • A for loop iterating through the array, where you search the entire text for the word and then replace it with @CharlotteDunois method. It's definitely much slower than searching the text 1 time, but its relatively simple. Commented Aug 12, 2015 at 16:02
  • Use preg_replace : php.net/manual/en/function.preg-replace.php Commented Aug 12, 2015 at 16:07
  • 1
    str_replace(), substr_replace(), strtr(), preg_replace()? Commented Aug 12, 2015 at 16:41

3 Answers 3

1

Create a pattern from you words

Method 1

$search = array(
     0 => "hello",
     1 => "author",
     2 => "cars",
    );
$replace =  '<a alt="MATCH" href="/link/MATCH">MATCH</a>';

$patt = '/\b('.implode('|', $search).')/i';
$subject = preg_replace($search, $replace, $subject);

Method 2

 str_ireplace( $search, $replace, $subject);

Method 2 is simpler, but less useful in that it's harder to back reference the matched words.

Bit confused if you want MATCH or the text that matched. If you want the text that matched use Method1 and this for the replace

 $replace =  '<a alt="$1" href="/link/$1">$1</a>';

For example

https://regex101.com/r/pL4iA4/2

Just to explain how this works, the pattern should look like this

 '/\b(hello|author|cars)/i'

So what that means in plain English is

  • \b word boundary ( space or special characters )
  • ( ) parentheses capture group
  • individual words are literal matches
  • | the or operator
  • /i case insensitive

So basically capture any words that start with word list

Sign up to request clarification or add additional context in comments.

3 Comments

PHP Storm gives me errors when I use this: $patt = '/\b('.implode('|', $search)).')\b/i'; I changed it to: $search = '/\b('.implode('|', $users).')\b/i'; right?
sure, there is an extra ) that's what happens when you just type it in to the box. Sorry I'll update it.
@Clank - what do you mean, this is a pattern for begins with match that is case insensitive flag /i
0
$text = // ...

$listOfPhrasesThatShouldBeLinks = [
    'hello',
    'author',
    'cars'
];

$quotedListForRegex = array_map(
    function ($phrase) {
        return preg_quote($phrase);
    },
    $listOfPhrasesThatShouldBeLinks
);

$regex = '(' . implode('|', $quotedListForRegex) . ')/i';

$textWithLinks = preg_replace_callback(
    $regex,
    function (array $matches) {
        $escapedMatch = htmlentities($matches[1]);
        return '<a alt="' . $escapedMatch . '" href="/link/' . $escapedMatch . '">' . $escapedMatch . '</a>';
    },
    $text
);

Comments

0

You can try this:

    <?php

    $a=array(
     0 => "hello",
     1 => "author",
     2 => "cars",
    );

    $text = 'Lorem ipsum dolor sit amet, cons etetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos e t accusam et jus to duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata s anctus est Lorem ipsum dolor hello sit amet. Lorem ipsum dolor sit a met, consetetur sadip scing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed di am voluptua. carsAt vero eos et accusam et justo duo dolores et ea rebum. Stet clita author, kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.';
    $text = str_ireplace($a,'<a alt="MATCH" href="/link/MATCH">MATCH</a>',$text);
    echo $text;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.