Link'; echo addcslashes($string, '"'); but the output is Link instead" /> Link'; echo addcslashes($string, '"'); but the output is Link instead" /> Link'; echo addcslashes($string, '"'); but the output is Link instead"/>

Add slash before double quotes php

835 views Asked by At
$string = '<a href="https://google.com">Link</a>';
echo addcslashes($string, '"');

but the output is

<a href="\"https://google.com\"">Link</a>

instead should be like this

<a href=\"https://google.com\">Link</a>

or if this is not the right solution then maybe replace the double quote with a single quote

This is how I'm using it, this is for a schema that I am currently doing and the double quotes is messing it all up

global $post;
$guide_style = get_field('guide_style');

if ($guide_style == 'Detailed') {
    $content_rows = 'flexible_content';
} else {
    $content_rows = 'flexible_content_general';
}

$ho = get_field_object($content_rows);

if ($ho) {
    foreach ($ho['value'] as $value) {
        if ($value['questions_&_answer']) {
        $hillo = count($value['questions_&_answer']);
        //var_dump($value['questions_&_answer']);
        }
    }
}

if( have_rows($content_rows) ):
    while(the_flexible_field($content_rows)):
        if( have_rows('questions_&_answer') ): ?>
        <script type="application/ld+json">
        {
            "@context":"https://schema.org",
            "@type":"FAQPage",
            "mainEntity":[
        <?php $faqs = get_sub_field('questions_&_answer');
        $rowCount = $hillo;
        $comma = ',';
        $i = 1;
        while ( have_rows('questions_&_answer') ) : the_row();?>
        {"@type":"Question","name":"<?=get_sub_field('question', false, false)?>","acceptedAnswer":{"@type":"Answer","text":"<?=addcslashes(get_sub_field('answer', false, false), '"')?>"}}<?=($i < $rowCount) ? $comma : '';?><?php $i++; endwhile; ?>
            ]
        }
        </script>
        <?php 
        endif;
    endwhile;
endif;
1

There are 1 answers

7
l'L'l On

Try escaping the double-quote in addcslashes:

echo addcslashes($string, '\"');

It's unclear why it wouldn't work the way you currently have it; both methods work fine here:

https://repl.it/repls/ElderlyConfusedObjects

Using str_replace:

If the undesired resulting string looks like this:

<a href="\"https://google.com\"">Link</a>

You can remove the surrounding double-quotes by:

$string = str_replace(array('"\"', '\""'), '\"', $string);