Scott B
Scott B

Reputation: 40157

Case insensitive preg_replace_callback

In the function below, I want to match the keyword case insensitive (should match "Blue Yoga Mats" and "blue yoga mats")...

However, it currently only matches if the keyword is the same case.

$mykeyword = "Blue Yoga Mats";

$post->post_content = preg_replace_callback("/\b($mykeyword)\b/","doReplace", $post->post_content);

// the callback function
function doReplace($matches)
{
    static $count = 0;

    // switch on $count and later increment $count.
    switch($count++) {
        case 0: return '<b>'.$matches[1].'</b>';   // 1st instance, wrap in bold
        case 1: return '<em>'.$matches[1].'</em>'; // 2nd instance, wrap in italics
        case 2: return '<u>'.$matches[1].'</u>'; // 3rd instance, wrap in underline
        default: return $matches[1];              // don't change others.
            }
    }

Upvotes: 0

Views: 921

Answers (5)

Danon
Danon

Reputation: 2973

You can also use T-Regx library:

<?php
pattern('\b($mykeyword)\b')->replace($post->post_content)->callback('doReplace');
      // ↑ Delimiters are not required 

Also, use of $mykeyword might cause user-input characters to break your pattern. With T-Regx you can use Prepared Patterns and just build your pattern:

<?php
$pattern = Pattern::inject("\b(@keyword)\b", [
    'keyword' => $mykeyword  
    // quoting unsafe characters
]);
$pattern->replace($post->post_content)->callback('doReplace');

Upvotes: 0

BoltClock
BoltClock

Reputation: 723578

Simply add the i modifier to your regex to make it perform a case insensitive match:

"/\b($mykeyword)\b/i"

By the way, if you haven't already, you need to escape special regex characters from your keyword. In case any are present, they could screw up your regex and cause PHP warnings/errors. Call preg_quote() before you perform the replacement:

$mykeyword_escaped = preg_quote($mykeyword, '/');
$post->post_content = preg_replace_callback("/\b($mykeyword_escaped)\b/i","doReplace", $post->post_content);

Upvotes: 3

William Linton
William Linton

Reputation: 860

Use the /i modifier:

$post->post_content = preg_replace_callback("/\b($mykeyword)\b/i","doReplace", $post->post_content);

Upvotes: 0

danlefree
danlefree

Reputation: 478

$post->post_content = preg_replace_callback("/\b($mykeyword)\b/i","doReplace", $post->post_content);

Use TOKENregexpTOKENi to perform case-insensitive searches.

See Pattern Modifiers in the PHP manual for full details on modifiers.

Upvotes: 0

icanhasserver
icanhasserver

Reputation: 1064

Add the "i" modifier to your regexp:

/\b($mykeyword)\b/i

Upvotes: 0

Related Questions