1

i have php variables that is like this

var externalData = '<?php echo $matches[0]; ?>';

I when i load the source code of the page comes like this

var externalData = 'data,data,data,data,data
';

this breaks the javascript code, and browser cant run it.

I want to be like this:

var externalData = 'data,data,data,data,data';

the php output is a full line of a file, so may contains the end of the line. I test it by hand and working, how i can fix this?

4
  • 3
    What is that closing parenthesis doing there? Commented Aug 11, 2013 at 13:14
  • sorry just error typing, i remove the parenthesis. Commented Aug 11, 2013 at 13:17
  • You should escape the result of $matches[0]. Also the ')' is not valid javascript so it is normal that it will break. Commented Aug 11, 2013 at 13:18
  • This is a bad practice. Serialize your PHP data to JSON via json_encode(), then parse it client side via JSON.parse, possibly from a <script type="application/json" id="yourAwesomeId"></script> tag [see this answer]. Commented Aug 11, 2013 at 13:29

3 Answers 3

4

You can use trim (or rtrim) to remove the line break at the end of the string:

var externalData = "<?php echo trim($matches[0]); ?>";

Alternatively you could pass the whole string to json_encode:

var externalData = <?php echo json_encode($matches[0]); ?>;

This would not remove the line break, but it would encode it and the resulting value will be a valid JS string literal (i.e. all other characters that could break the code, such as ' or ", will escaped as well).

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe you should strip all HTML

var externalData = "<?php echo strip_tags($matches[0];) ?>");

1 Comment

Line endings to not get stripped, which is the issue here.
0

You can also use substr() to get rid of the last char of string.

Like this:

var externalData = "<?php echo substr($matches[0], 0, strlen($matches[0]) - 1); ?>";

3 Comments

Won't work if the break is actually \r\n (windows). Also substr($blah,0,-1) is more elegant.
@Dave Thank you! If it runs on windows. substr($blah,0,-2) may be OK
it's not about what it runs on, but where the newline is coming from in the first place. If it's known for sure, then yes this would be fine. If it's uncertain, rtrim is probably the better option.

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.