Viewed   67 times

In PHP I am trying to create a newline character:

echo $clientid;
echo ' ';
echo $lastname;
echo ' ';
echo 'rn';

Afterwards I open the created file in Notepad and it writes the newline literally:

1 John Doern 1 John Doern 1 John Doern

I have tried many variations of the rn, but none work. Why isn't the newline turning into a newline?

 Answers

1

Only double quoted strings interpret the escape sequences r and n as '0x0D' and '0x0A' respectively, so you want:

"rn"

Single quoted strings, on the other hand, only know the escape sequences \ and '.

So unless you concatenate the single quoted string with a line break generated elsewhere (e. g., using double quoted string "rn" or using chr function chr(0x0D).chr(0x0A)), the only other way to have a line break within a single quoted string is to literally type it with your editor:

$s = 'some text before the line break
some text after';

Make sure to check your editor for its line break settings if you require some specific character sequence (rn for example).

Wednesday, August 24, 2022
3
$string = "abc123";
$random_position = rand(0,strlen($string)-1);
$chars = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789-_";
$random_char = $chars[rand(0,strlen($chars)-1)];
$newString = substr($string,0,$random_position).$random_char.substr($string,$random_position);
echo $newString;
Friday, August 19, 2022
 
5

Parsing HTML using regex is a pain at best as HTML is not regular, I suggest you use Simple HTML DOM.

Saturday, October 29, 2022
 
embo
 
4

From a speed point of view, to differentiate concatenation (value1 + "-" + value2) and interpolation ("(value1)-(value2)"), results may depend on the number of operations done to obtain the final string.

My results on an iPhone 8 show that:

  • if there is roughly < 30 substrings to attach together, then concatenation is faster
  • if there is roughly > 30 substrings to attach together, then interpolation is faster

Thank you Sirens for figuring out that one wasn't always faster than the other!

Try it yourself (and don't forget to adapt the tested character set and iterations for your needs):

import UIKit

class ViewController: UIViewController {
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        DispatchQueue.global(qos: .default).async {
            ViewController.buildDataAndTest()
        }
    }

    private static func buildDataAndTest(times: Int = 1_000) {
        let characterSet = CharacterSet.alphanumerics
        characterSet.cacheAllCharacters()
        let data: [(String, String)] = (0 ..< times).map { _ in
             (characterSet.randomString(length: 50), characterSet.randomString(length: 20))
        }
        _ = testCIA(data)
        _ = testInterpol(data)
        print("concatenation: " + String(resultConcatenation))
        print("interpolation: (resultInterpolation)")
    }

    /// concatenation in array
    static var resultConcatenation: CFTimeInterval = 0
    private static func testCIA(_ array: [(String, String)]) -> String {
        var foo = ""
        let start = CACurrentMediaTime()
        for (a, b) in array {
            foo = foo + " " + a + "+" + b
        }
        resultConcatenation = CACurrentMediaTime() - start
        return foo
    }

    /// interpolation
    static var resultInterpolation: CFTimeInterval = 0
    private static func testInterpol(_ array: [(String, String)]) -> String {
        var foo = ""
        let start = CACurrentMediaTime()
        for (a, b) in array {
            foo = "(foo) (a)+(b)"
        }
        resultInterpolation = CACurrentMediaTime() - start
        return foo
    }
}

extension CharacterSet {
    static var cachedCharacters: [Character] = []

    public func cacheAllCharacters() {
        CharacterSet.cachedCharacters = characters()
    }

    /// extracting characters
    /// https://.com/a/52133647/1033581
    public func characters() -> [Character] {
        return codePoints().compactMap { UnicodeScalar($0) }.map { Character($0) }
    }
    public func codePoints() -> [Int] {
        var result: [Int] = []
        var plane = 0
        for (i, w) in bitmapRepresentation.enumerated() {
            let k = i % 8193
            if k == 8192 {
                plane = Int(w) << 13
                continue
            }
            let base = (plane + k) << 3
            for j in 0 ..< 8 where w & 1 << j != 0 {
                result.append(base + j)
            }
        }
        return result
    }

    // http://.com/a/42895178/1033581
    public func randomString(length: Int) -> String {
        let charArray = CharacterSet.cachedCharacters
        let charArrayCount = UInt32(charArray.count)
        var randomString = ""
        for _ in 0 ..< length {
            randomString += String(charArray[Int(arc4random_uniform(charArrayCount))])
        }
        return randomString
    }
}
Wednesday, August 3, 2022
 
mtrompe
 
4

The obvious answer is that there are times when you might not want variables to be interpreted in your strings.

Take, for example, the following line of code:

$currency = "$USD";

This produces an "undefined variable" notice and $currency is an empty string. Definitely not what you want.

You could escape it ("$USD"), but hey, that's a faff.

So PHP, as a design decision, chose to have double-quoted strings interpolated and single-quoted strings not.

Wednesday, August 3, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share