Simon Arnold
Simon Arnold

Reputation: 16177

String replacement with potential parentheses in the string

Let say I have a var $text:

Lorem ipsum dolor sit amet. John Doe Ut tincidunt, elit ut sodales molestie.

and a var $name:

John Doe

I need to found out all occurrences of $name in $text and add an href around it.
Which I currently do with str_replace.

But what if there is parentheses in the name?
Let say var $text look like this instead:

Lorem ipsum dolor sit amet. John (Doe) Ut tincidunt, elit ut sodales molestie.

or

Lorem ipsum dolor sit amet. (John) Doe Ut tincidunt, elit ut sodales molestie.

How can I still found $name with thoses parentheses?

Upvotes: 0

Views: 89

Answers (3)

Alexander Mohorev
Alexander Mohorev

Reputation: 135

$text = "Lorem ipsum dolor sit amet. (John) Doe Ut tincidunt, elit ut sodales molestie.";

$name = "John Doe";

function createUrl($matches) {
    $name = $matches[0];
    $url = str_replace(['(', ')'], '', $matches[0]);
    return "<a href='index.php?name={$url}'>{$name}</a>";
}
$pattern = str_replace(' ', '\)? \(?', $name);
echo preg_replace_callback("/(\(?$pattern\)?)/", 'createUrl', $text);

Upvotes: 1

user1986815
user1986815

Reputation:

another version that use just preg_split

$split=preg_split('/\s+/', $name);
$frst=$split[0];
$mid=$split[1];
$lst=$split[2];

another posibility is using ucwords

$split=ucwords($name);
$frst=$split[0];
$mid=$split[1];
$lst=$split[2];

and then

preg_replace('.?$frst.? .?$mid.? .?$lst.?',$replacement,$text);

works also with other type of delimiters [{()}] etc ...

Upvotes: 0

Jay Harris
Jay Harris

Reputation: 4271

split the name by first and last name.

$split = explode(' ', $name);
$first = $split[0];
$last  = $split[1];


preg_replace(
  "/(\(?($first)\)? \(?($last)\))/"
, $replacement
, $text
);

a more dynamic approach

// split name string into sub-names
$split = explode(' ', $name);

// initiate the search string 
$search = '';

// loop thru each name
// solves the multiple last or middle name problem     
foreach ($split as $name) {
  // build the search regexp for each name
  $search .= " \(?$name\)?";
}

// remove first space character
$search = substr($search, 1);

// preg_replace() returns the string after its replaced
// note: $replacement isn't defined, left it for you :)

// note: the replacement will be lost if you don't
//  print/echo/return/assign this statement.
preg_replace(
  "/($search)/"
, $replacement
, $text
);

Upvotes: 2

Related Questions