Solved

Javascript equivalent for this php function

Posted on 2013-11-04
18
683 Views
Last Modified: 2013-11-11
Can you write a javascript or jquery method that would accomplish the exact same function as this php method please?

    var $wordSeparator = '-';

    private function getStringAsNiceName($string) {
		//strip tags, trim, and lowercase
		$string = strtolower(trim(strip_tags($string)));
		//replace single quotes and double quotes first
		$string = preg_replace('/[\']/i', '', $string);
		$string = preg_replace('/["]/i', '', $string);

		$string = preg_replace('/&/', 'and', $string);

		//remove non-valid characters
		$string = preg_replace('/[^-a-z0-9]/i', $this->wordSeparator, $string);
		$string = preg_replace('/-[-]*/i', $this->wordSeparator, $string);

		//remove from beginning and end
		$string = preg_replace('/' . $this->wordSeparator . '$/i', '', $string);
		$string = preg_replace('/^' . $this->wordSeparator . '/i', '', $string);

		return $string;

Open in new window


This is a method I use in order to convert strings into URL friendly strings.
0
Comment
Question by:aristanoble
  • 9
  • 4
  • 4
  • +1
18 Comments
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 39623612
http://phpjs.org/ may help, it is a resource that offers community-built JavaScript alternatives to PHP functions.
0
 
LVL 1

Author Comment

by:aristanoble
ID: 39623619
Thank you but I need this particular custom function converted because I use it on the server so I need the same result to appear on the client when I want to show a preview of the final url.
0
 
LVL 9

Expert Comment

by:Sar1973
ID: 39623818
Try to use string.replace(new RegExp('oldString', 'gi'), "newString"); for punctual replacement and the JS trim function (see http://www.w3schools.com/jsref/jsref_trim_string.asp).
0
 
LVL 1

Author Comment

by:aristanoble
ID: 39624763
Thanks but my regex coding isn't very strong that's why I wanted to rely on an expert. From what I can tell your solution only achieves part of the goal. Can you provide an efficient snippet of javascript or jquery code that would return the same filtered string as the above php getStringAsNiceName function?
0
 
LVL 9

Expert Comment

by:Sar1973
ID: 39624851
If you use the JS functions step by step, you should be able to replicate the php function.
0
 
LVL 1

Author Comment

by:aristanoble
ID: 39624877
I think it's more salient to you because of your experience but for me it doesn't seem that straight forward to just follow the JS functions step by step and I'll confidently and precisely replicate the php function and it's regular expressions. I would really prefer an expert to whip up an efficient snippet that I can trust with confidence; unless I'm asking for too much.
0
 
LVL 33

Expert Comment

by:Slick812
ID: 39625261
greetings  aristanoble, you have several many things in your PHP code that are not a known spec (value) like -
$this->wordSeparator

it may can help (at least for me)  if you give in plain Talk what exactly you need for -
//remove non-valid characters
      you have TWO preg_replace( ) for this, and I would think you could do it with ONE replacement, if you can better define the output from this as it appears to allow the alphabet, the numbers 0 to 9, but I am not sure about the second  preg_replace( )  with a - spec, , , as I said there is the $this->wordSeparator in these, is this a FIXED value like a space character or a variable thing, depending on other settings?

also not sure about the -
//remove from beginning and end
as a preg_replace( ) , seems like the php trim thing already did this?
do you know, and can you tell us exactly what needs to be = //remove from beginning and end
0
 
LVL 1

Author Comment

by:aristanoble
ID: 39625331
Well it's actually part of a class. $this->wordSeparator is calling the $wordSeparator property declared as "var $wordSeparator = '-';". It basically allows me to take any string and make it URL friendly. My objective is to use this method on the server but to show a preview on the client side using javascript. The preview must match the expected return on the server so the JS function must escape, format and filter the same as the php method. (Of course, I could make an ajax call to the server but I see no reason why I couldn't just do this in javascript client side)

<?php

class prettyName {

    var $wordSeparator = '-';

    public function getStringAsNiceName($string) {
		//strip tags, trim, and lowercase
		$string = strtolower(trim(strip_tags($string)));
		//replace single quotes and double quotes first
		$string = preg_replace('/[\']/i', '', $string);
		$string = preg_replace('/["]/i', '', $string);

		$string = preg_replace('/&/', 'and', $string);

		//remove non-valid characters
		$string = preg_replace('/[^-a-z0-9]/i', $this->wordSeparator, $string);
		$string = preg_replace('/-[-]*/i', $this->wordSeparator, $string);

		//remove from beginning and end
		$string = preg_replace('/' . $this->wordSeparator . '$/i', '', $string);
		$string = preg_replace('/^' . $this->wordSeparator . '/i', '', $string);

		return $string;
        }
}
?>

$prettyName = new prettyName();
$name = $prettyName->getStringAsNiceName('hello world'); //e.g. returns "hello-world",

Open in new window

0
 
LVL 33

Expert Comment

by:Slick812
ID: 39625453
yes I already know that this is in a CLASS declaration , and thanks for saying that the value for $this->wordSeparator is "-"

and I take it that this class is not something that you wrote, so you can not tell me about what is the functioning of the -
//remove non-valid characters
preg_replace( ) things.

OK, I really do not have the time now to do BOTH, as in write some javascript and then have to put your class in a PHP page and then run a hundred of different strings with different characters and <b> html tags and " and ' and other, to see if the getStringAsNiceName( ) and my JS will deliver the same output. Sorry about that. . .
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 1

Author Comment

by:aristanoble
ID: 39625491
Oh that sounds like overkill and more than what I'm asking for. I had assumed using the comments as guides and using similar if not the same reg expressions your final JavaScript function would then yield the same output. No?
0
 
LVL 9

Expert Comment

by:Sar1973
ID: 39626705
As said before, I suggest you to take a look to the complete JS string reference at http://w3schools.com/jsref/jsref_obj_string.asp
0
 
LVL 1

Author Comment

by:aristanoble
ID: 39627071
Ok, I will thank you. But as for answering my question so that I can award points and close the question, are you saying that an expert couldn't use similar, if not the same, regex patterns and the comments as their guide in order to produce a good javascript equivalent? Please let me know and I'll close this question as being unanswerable. Or maybe assign the points to myself :)

Just to clarify, I'm assuming these comments:
//strip tags, trim, and lowercase
//replace single quotes and double quotes first
//remove non-valid characters
//remove from beginning and end
and these patterns:
/[\']/i
/["]/i
/&/
/[^-a-z0-9]/i
/-[-]*/i
/' . $this->wordSeparator . '$/i
/^' . $this->wordSeparator . '/i
should be able to assist any expert that knows javascript and has strong regex abilities to create a javascript function that returns url friendly strings of text.

One could even treat this as if I had never spoke of a php function and simply requested that an expert would take these comments and patterns as a guide to produce such a function.
0
 
LVL 9

Expert Comment

by:Sar1973
ID: 39627138
The regular expression function allows you to define both criteria and type of characters you want to replace inside the string (for example /i for case-insensitive matching, /[^-a-z0-9]/ for any characters and digits).
0
 
LVL 1

Author Comment

by:aristanoble
ID: 39627151
Thank you Sar, that was helpful. Once an expert replies to my question with a javascript function that meets the objective; I'll award the necessary points and close it out.
0
 
LVL 33

Expert Comment

by:Slick812
ID: 39628474
@ aristanoble, , You seem to think that this is a simple thing, and yet you have not posted any Trial javascript function that you wrote, so we can advise you on how to make it work better. NO one else has posted any javascript to do the task, so maybe it anit so easy. Although the separate lines of code going preg_replace( ) in the PHP method are not individually difficult as a RegExpression, BUT the combined changing of the string with all of the 10 different string parses can be difficult to know if the final string in javascript will match the final string in the PHP, just by lookin at the PHP and javascript function code, as I tried to say to you, it takes time and effort to run may different strings through the PHP and JS to see if they all match, and then do experiments to get the JS output to match.
If you just want a javascript function that has NOT been tested against the PHP function, then here is my screwball attempt -
function makeURL(inStr){
inStr= inStr.trim(inStr);
inStr= inStr.toLowerCase(inStr);
inStr = inStr.replace(/<\/?[^>]+(>|$)/g, "");
inStr = inStr.replace("'", "");
inStr = inStr.replace('"', "");
inStr = inStr.replace(/[^\-a-z0-9]/g, "-");
inStr = inStr.replace(/-{2,}/g, "-");
inStr = inStr.replace(/^-/, "");
inStr = inStr.replace(/-$/, "");
return inStr;
}

Open in new window

I DID NOT TEST this JS against any thing of your PHP method, it's just a guess at what I think the PHP does.

I have this -
inStr = inStr.replace(/<\/?[^>]+(>|$)/g, "");
for the PHP strip_tags( ) however I know from using the strip_tags( ) that the function uses a much more significant string parse to remove tags than the simplistic  /<\/?[^>]+(>|$)/g   BUT as long as the HTML tags are properly formed then this javascript should work OK, but if there are tags without closing or tags within tags, then they will NOT match.
You do not seem to have any skill with javascript, ask questions if you need more help wid JS
0
 
LVL 1

Accepted Solution

by:
aristanoble earned 0 total points
ID: 39628481
You're right; I don't have any skill with javascript and this does look like a very screwball attempt.
0
 
LVL 33

Expert Comment

by:Slick812
ID: 39628504
I tested as such -

var strInput = "#<h2>About \"is' 5&p+ </h2> <p>M*******<a href=\"/about\">Re-ad more</a></p>%";
var noTags = makeURL(strInput);
document.getElementById("dv0").innerHTML = "NO TAGS= "+noTags;

it returns -
about-is-5-p-m-re-ad-more

++++++

you should at least try my function, it does the job , as far as I can tell, you need to spend your own time, comparing the results for the JS and your PHP for different strings, but if your converted strings are as simple as you only example "Hello World" then it'll work
0
 
LVL 1

Author Closing Comment

by:aristanoble
ID: 39638308
Based on the expert's suggestions, screwball attempt, and my "lack of ANY skill in javascript" this question was deemed unanswerable, untestable, and couldn't produce the php equivalent result I was looking for. I'll come up with the solution on my own.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now