PyQL
PyQL

Reputation: 1830

replace everything except specific words in PHP

Is it possible to use php's preg_replace to remove anything in a string except specific words?

For example:

$text = 'Hello, this is a              test string from php.';

I want to remove everything except "test" and "php" so it will be:

$text will be 'test php'

Upvotes: 0

Views: 2251

Answers (3)

https://gist.github.com/oleksandr-andrushchenko/68d7382fb917dd4eb66ac8ca9bd84006

addWordSecrets('Secret all words'), // ****** *** *****
addWordSecrets('Secret all, except; kept, kept2 and kept3 word', excepts: ['kept, kept2', 'kept3']), // ****** ***, ******; kept, kept2 *** kept3 ****
addWordSecrets('Any language & two-way case insensitive: Україна україна', excepts: ['укРАЇна']), // *** ******** & ***-*** **** ***********: Україна україна
addWordSecrets('Percents * percents', excepts: '*', char: '%'), // %%%%%%%% * %%%%%%%%

Upvotes: 0

Xeoncross
Xeoncross

Reputation: 57284

$text = 'Hello, this is a              test string from php.';
$words = preg_split('~\W~', $text, -1, PREG_SPLIT_NO_EMPTY);

$allowed_words = array('test'=>1, 'php'=>1);
$output = array();
foreach($words as $word)
{
    if(isset($allowed_words[$word]))
    {
        $output[] = $word;
    }
}

print implode(' ', $output);

Upvotes: 0

outis
outis

Reputation: 77450

You could always use a callback. Under PHP 5.3:

$keep = array('test'=>1, 'php'=>1);

$text = trim(
    preg_replace(
        '/[^A-Za-z]+/', ' ',
        preg_replace_callback(
            '/[A-Za-z]+/',
            function ($matched) use (&keep) {
                if (isset($keep[$matched[0]])) {
                    return $matched[0];
                }
                return '';
            }, $text
            )   )            );

Alternatively:

$text = 
    array_intersect(
        preg_split('/[^A-Za-z]+/', $text),
        array('test', 'php')
    );

Upvotes: 1

Related Questions