JoaMika
JoaMika

Reputation: 1827

Include php preg_replace in string

I am trying to include a php function within a string but my syntax is wrong. Could anyone help please?

$string = "<div id=\"apostnav\"><span class=\"calcir b-" . $string=get_field('br_category');
$string=preg_replace("/[^a-zA-Z]/", "", $string);
echo strtolower($string) . "></span></div>";

Upvotes: 1

Views: 51

Answers (2)

user2342558
user2342558

Reputation: 6712

Try this:

$string=get_field('br_category');
$string=preg_replace("/[^a-zA-Z]/", "", $string);

$string = "<div id=\"apostnav\"><span class=\"calcir b-" . strtolower($string) . "\"></span></div>";

I moved up two lines of code andn removed an echo from the last one.

Here the code with few optimizations:

$string = get_field('br_category');
$string = preg_replace("/[^a-zA-Z]/", '', $string);
$stringLower = strtolower($string);

$string = "<div id='apostnav'><span class='calcir b-$stringLower'></span></div>";

Upvotes: 2

marcell
marcell

Reputation: 1528

You can use printf too in order to print your html string with the variable:

printf('<div id="apostnav"><span class="calcir b-%s"></span></div>', strtolower(preg_replace('/[^a-zA-Z]/', '', get_field('br_category'))));

Upvotes: 1

Related Questions