开发者

PHP equivalent to JavaScript's string split method

I'm working with this on JavaScript:

<script type="text/javascript">
    var sURL = "http://itunes.apple.com/us/app/accenture-application-for/id415321306?uo=2&mt=8&uo=2";
    splitURL = sURL.split('/');
    var appID = splitURL[splitURL.length - 1].match(/[0-9]*[0-9]/)[0];
    document.write('<br /><strong>Link Lookup:</strong> <a href="http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsLookup?id=' + appID + '&country=es" >Lookup</a><br />');
</script>

T开发者_如何学Gohis script takes the numeric ID and gives me 415321306.

So my question is how can I do the same thing but using PHP.

Best regards.


Use PHP's explode() function instead of .split().

splitURL = sURL.split('/');  //JavaScript

becomes

$splitURL = explode('/', $sURL);  //PHP

An use preg_match() instead of .match().

$appID = preg_match("[0-9]*[0-9]", $splitURL);

I'm a little unclear on what you're doing with the length of the string, but you can get substrings in php with substr().


Who needs regex?

<?php
    $sURL = "http://itunes.apple.com/us/app/accenture-application-for/id415321306?uo=2&mt=8&uo=2";
    $appID = str_replace('id','',basename(parse_url($sURL, PHP_URL_PATH)));
    echo $appID; // output: 415321306
?>


preg_match("/([0-9]+)/",$url,$matches);
print_r($matches);


The two functions you desire are:

  • http://www.php.net/manual/en/function.preg-split.php
  • http://www.php.net/manual/en/function.preg-match.php


Javascript split can also be used to convert a string into a character array (empty argument) and the first argument can be a RegExp.

/*

Example 1

This can be done with php function str_split();

*/

var str = "Hello World!"

str.split('');

H,e,l,l,o, ,W,o,r,l,d,!

/*

Example 1

This can be done with php function preg_split();

*/

var str = " \u00a0\n\r\t\f\u000b\u200b";

str.split('');

, , , , ,,,​

From Ecma-262 Returns an Array object into which substrings of the result of converting this object to a String have been stored. The substrings are determined by searching from left to right for occurrences of separator; these occurrences are not part of any substring in the returned array, but serve to divide up the String value. The value of separator may be a String of any length or it may be a RegExp object (i.e., an object whose [[Class]] internal property is "RegExp"; see 15.10). The value of separator may be an empty String, an empty regular expression, or a regular expression that can match an empty String. In this case, separator does not match the empty substring at the beginning or end of the input String, nor does it match the empty substring at the end of the previous separator match. (For example, if separator is the empty String, the String is split up into individual characters; the length of the result array equals the length of the String, and each substring contains one character.) If separator is a regular expression, only the first match at a given position of the this String is considered, even if backtracking could yield a non-empty-substring match at that position. (For example, "ab".split(/a*?/) evaluates to the array ["a","b"], while "ab".split(/a*/) evaluates to the array["","b"].) If the this object is (or converts to) the empty String, the result depends on whether separator can match the empty String. If it can, the result array contains no elements. Otherwise, the result array contains one element, which is the empty String. If separator is a regular expression that contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array.


javascript equivalent functions to php (http://kevin.vanzonneveld.net)

<script>
  function preg_split (pattern, subject, limit, flags) {
        // http://kevin.vanzonneveld.net
        // + original by: Marco Marchi??
        // * example 1: preg_split(/[\s,]+/, 'hypertext language, programming');
        // * returns 1: ['hypertext', 'language', 'programming']
        // * example 2: preg_split('//', 'string', -1, 'PREG_SPLIT_NO_EMPTY');
        // * returns 2: ['s', 't', 'r', 'i', 'n', 'g']
        // * example 3: var str = 'hypertext language programming';
        // * example 3: preg_split('/ /', str, -1, 'PREG_SPLIT_OFFSET_CAPTURE');
        // * returns 3: [['hypertext', 0], ['language', 10], ['programming', 19]]
        // * example 4: preg_split('/( )/', '1 2 3 4 5 6 7 8', 4, 'PREG_SPLIT_DELIM_CAPTURE');
        // * returns 4: ['1', ' ', '2', ' ', '3', ' ', '4 5 6 7 8']
        // * example 5: preg_split('/( )/', '1 2 3 4 5 6 7 8', 4, (2 | 4));
        // * returns 5: [['1', 0], [' ', 1], ['2', 2], [' ', 3], ['3', 4], [' ', 5], ['4 5 6 7 8', 6]]
    
        limit = limit || 0; flags = flags || ''; // Limit and flags are optional
    
        var result, ret=[], index=0, i = 0,
            noEmpty = false, delim = false, offset = false,
            OPTS = {}, optTemp = 0,
            regexpBody = /^\/(.*)\/\w*$/.exec(pattern.toString())[1],
            regexpFlags = /^\/.*\/(\w*)$/.exec(pattern.toString())[1];
            // Non-global regexp causes an infinite loop when executing the while,
            // so if it's not global, copy the regexp and add the "g" modifier.
            pattern = pattern.global && typeof pattern !== 'string' ? pattern :
                new RegExp(regexpBody, regexpFlags+(regexpFlags.indexOf('g') !==-1 ? '' :'g'));
    
        OPTS = {
            'PREG_SPLIT_NO_EMPTY': 1,
            'PREG_SPLIT_DELIM_CAPTURE': 2,
            'PREG_SPLIT_OFFSET_CAPTURE': 4
        };
        if (typeof flags !== 'number') { // Allow for a single string or an array of string flags
            flags = [].concat(flags);
            for (i=0; i < flags.length; i++) {
                // Resolve string input to bitwise e.g. 'PREG_SPLIT_OFFSET_CAPTURE' becomes 4
                if (OPTS[flags[i]]) {
                    optTemp = optTemp | OPTS[flags[i]];
                }
            }
            flags = optTemp;
        }
        noEmpty = flags & OPTS.PREG_SPLIT_NO_EMPTY;
        delim = flags & OPTS.PREG_SPLIT_DELIM_CAPTURE;
        offset = flags & OPTS.PREG_SPLIT_OFFSET_CAPTURE;
    
        var _filter = function(str, strindex) {
            // If the match is empty and the PREG_SPLIT_NO_EMPTY flag is set don't add it
            if (noEmpty && !str.length) {return;}
            // If the PREG_SPLIT_OFFSET_CAPTURE flag is set
            //      transform the match into an array and add the index at position 1
            if (offset) {str = [str, strindex];}
            ret.push(str);
        };
        // Special case for empty regexp
        if (!regexpBody){
            result=subject.split('');
            for (i=0; i < result.length; i++) {
                _filter(result[i], i);
            }
            return ret;
        }
        // Exec the pattern and get the result
        while (result = pattern.exec(subject)) {
            // Stop if the limit is 1
            if (limit === 1) {break;}
            // Take the correct portion of the string and filter the match
            _filter(subject.slice(index, result.index), index);
            index = result.index+result[0].length;
            // If the PREG_SPLIT_DELIM_CAPTURE flag is set, every capture match must be included in the results array
            if (delim) {
                // Convert the regexp result into a normal array
                var resarr = Array.prototype.slice.call(result);
                for (i = 1; i < resarr.length; i++) {
                    if (result[i] !== undefined) {
                        _filter(result[i], result.index+result[0].indexOf(result[i]));
                    }
                }
            }
            limit--;
        }
        // Filter last match
        _filter(subject.slice(index, subject.length), index);
        return ret;
    }
   </script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜