Mark Tower
Mark Tower

Reputation: 559

Matching substrings with placeholders

Definition:
I came across this scenario while working on PHP string Differences with Dynamic restrictions. It might be a reference to understand better what I want.

Problem:
Suppose I have a main string:

"This is a {1} string with {2} placeholders"

And a secondary one:

"This is a very similar string with data for the placeholders"

Question:
How could I get one variable for each placeholder, called $v1, $v2, $vn, whose values are "very similar" and "data for the", respectively? As you can see I need to assign to each placeholder the substring which is not in the main one.

Notes:
I am working with PHP.

Upvotes: 2

Views: 122

Answers (2)

Crisp
Crisp

Reputation: 11447

Use sprintf maybe?

$string = 'This is a %s string with %s placeholders';
$v1 = 'very similar';
$v2 = 'data for the';

$result = sprintf($string, $v1, $v2);

Upvotes: 0

Joshua Dwire
Joshua Dwire

Reputation: 5443

You should be able to use regex to do something like this:

$pattern="/This is a (.*) string with (.*) placeholders/";
$subject="This is a very similar string with data for the placeholders";

preg_match($pattern,$subject,$matches);

$v1=$matches[1];
$v2=$matches[2];

See http://php.net/manual/en/function.preg-match.php for more info on regex in php.

Upvotes: 2

Related Questions