0

There are 2 codes, PHP and JS. The work of the codes is exactly the same.

The duty of the codes is to count words. However, there is 1 difference between PHP and JS results.

The reason for this difference is due to the "line". How can I solve this problem.

I want both codes to give the same values.

PHP CODE:

PHP Result: 19

<?php

    function character_count($str){
        $str = preg_replace("/<\/?[a-z][^>]*>/i", "", $str);
        $str = preg_replace("/&nbsp;+/", " ", $str);
        $str = preg_replace("/\n+/", "", $str);
        $str = mb_strlen($str,'UTF-8');
        return $str;
    }
    
    $string = '<p>Hello World</p>
<p>Welcome</p>';
    
    echo character_count($string);

PHP CODE TEST: https://sandbox.onlinephpfunctions.com/code/64dac96d1406e2e7352858f8563f82378929eeb3


JS CODE:

JS Result: 18

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<h1></h1>

<script>
    function character_count(str){
        return str ? str.replace(/<\/?[a-z][^>]*>/gi, "").replace(/&nbsp;+/g, " ").replace(/\n+/, "").length : 0;
    }
    
    var string = '<p>Hello World</p>\n' +
        '<p>Welcome</p>';
    
    $("h1").text(character_count(string));    
</script>

12
  • 2
    the string is not same, in php you have a space between two <p> in js no. Commented Sep 29, 2020 at 6:24
  • You mean the difference is because the php counts new lines too? If yes then change the replace(/\n+/, "") in the js function to the replace(/\n+/, " "). Then the problem will be solved Commented Sep 29, 2020 at 6:25
  • i think yes, if you try to delete that space the count is same. Commented Sep 29, 2020 at 6:26
  • the new line is counted too Commented Sep 29, 2020 at 6:29
  • @Ashkan The problem was resolved when I made the change you specified. I'm doing a few tries. Thanks Commented Sep 29, 2020 at 6:34

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.