Jack Hales
Jack Hales

Reputation: 1644

PHP Use Regex to match whitespace as well as empty characters

I'll start off with some code, this is my current setup:

$search = [
  '/\{\{\sSTRING\s\}\}/is',
  '/\{\{STRING\}\}/is'
];

$replace = [
  '<b>TEST_STRING</b>',
  '<b>TEST_STRING</b>'    
];

echo preg_replace( $search, $replace, "{{STRING}}" );

This would then output TEST_STRING, as wanted, but I'm using two REGEX statements to make this work, and I want this to work with strings like {{ STRING }} as well as {{STRING}} by only using a single REGEX.

I thought the statement would also ignore there being whitespace, but the \s statement specifically looks for anything relating to [\r\n\t\f\v ], is there an expression to use that will ignore whitespace as well as include it?

Upvotes: 1

Views: 90

Answers (1)

dobaniashish
dobaniashish

Reputation: 66

You can add an optional quantifier "?" after whitespace character "\s".

$search = '/\{\{\s?STRING\s?\}\}/is';

$replace = '<b>TEST_STRING</b>';

echo preg_replace( $search, $replace, "{{STRING}}" );

Hope this helps.

Upvotes: 2

Related Questions