Harmeet Singh
Harmeet Singh

Reputation: 43

How to replace string used multiple time between same 2 characters?

I have this text. My Name is (Name). I live in (Turkey).

I would like to replace whatever is in brackets with the input tag. Desired Output should be like :

My Name is INPUT TAG HERE. I live in INPUT TAG HERE.

Upvotes: 1

Views: 58

Answers (2)

Anthony
Anthony

Reputation: 2122

You can use the following code :

<?php
//Allow **all** characters except parenthesis
$regex = '/\([^\(\)]+\)/';
//The matching items will be replaced by this
$replacement = 'INPUT TAG HERE';
//Input string
$sentence = 'My Name is (Name). I live in (Turkey).';
echo preg_replace($regex, $replacement, $sentence);

Will output:

My Name is INPUT TAG HERE. I live in INPUT TAG HERE.

This code uses the preg_replace method to replace the strings using a regular expression.
All characters are allowed between brackets (spaces, letters, digits, whatever else), absolutely all except other parenthesis.

Upvotes: 1

nandal
nandal

Reputation: 2634

Try the following:-

<?php
$string = 'My Name is (Name some). I live in (Turkey).';
// this pattern takes care of white spaces in multi word keywords inside () also
$pattern = '(\([\w\s]+\)*)';
$replacement = 'INPUT TAG HERE';
echo preg_replace($pattern, $replacement, $string);
?>

OUTPUT:- My Name is INPUT TAG HERE. I live in INPUT TAG HERE.

this pattern takes care of white spaces in multi word keywords inside () also

Upvotes: 1

Related Questions