1

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>";
4
  • You can't define a new variable inside another variable definition. Commented Dec 2, 2019 at 11:12
  • @user2342558 although meaningless (the value of $string is immediately overwritten) that is perfectly valid PHP. 3v4l.org/tuZTh Commented Dec 2, 2019 at 11:43
  • @Nick Ahh, I just learned something interesting :) thanks Commented Dec 2, 2019 at 11:53
  • 1
    @user2342558 I do think your answer is actually what OP wants, it's just that statement which is incorrect. Commented Dec 2, 2019 at 11:55

2 Answers 2

2

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>";
Sign up to request clarification or add additional context in comments.

Comments

1

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'))));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.