Completed
Push — master ( 33cdc3...038af3 )
by Lorenzo
01:59
created

string.php ➔ str_replace_array()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 3
dl 0
loc 8
rs 9.4285
1
<?php
2
3
/**
4
 * Strip new line breaks from a string
5
 * @param $str
6
 * @return string|array
7
 */
8
function strip_nl($str)
9
{
10
    return str_replace("\n", "", str_replace("\r", "", $str));
11
}
12
13
/**
14
 * Generate random string from [0-9A-Za-z] charset.
15
 * You may extend charset by passing $extChars.
16
 * Ex.: $extChars='-_&$!+'
17
 * @param int $length
18
 * @param string $extChars
19
 * @return string
20
 */
21
function generateRandomString(int $length = 10, string $extChars = '') : string
22
{
23
    if ($length < 1) {
24
        $length = 1;
25
    }
26
27
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
28
    if ($extChars !== null && $extChars != '') {
29
        $characters .= $extChars;
30
    }
31
32
    $charactersLength = strlen($characters);
33
    $randomString = '';
34
35
    for ($i = 0; $i < $length; $i++) {
36
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
37
    }
38
39
    return $randomString;
40
}
41
42
/**
43
 * Javascript escape
44
 * @param string $str
45
 * @return string
46
 * @source https://github.com/rtconner/laravel-plusplus/blob/laravel-5/src/plus-functions.php
47
 */
48
function jse(string $str) : string
49
{
50
    if ($str === null || $str == '') {
51
        return '';
52
    }
53
    $str = str_replace("\n", "", str_replace("\r", "", $str));
54
    return addslashes($str);
55
}
56
57
if (!function_exists('gravatar')) {
58
    /**
59
     * Get a Gravatar URL from email.
60
     *
61
     * @param string $email The email address
62
     * @param int $size in pixels, defaults to 80px [ 1 - 2048 ]
63
     * @param string $default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
64
     * @param string $rating (inclusive) [ g | pg | r | x ]
65
     * @return string
66
     * @source http://gravatar.com/site/implement/images/php/
67
     */
68
    function gravatar($email, $size = 80, $default = 'mm', $rating = 'g')
69
    {
70
        $url = 'http://www.gravatar.com/avatar/';
71
        $url .= md5(strtolower(trim($email)));
72
        $url .= "?s=$size&d=$default&r=$rating";
73
        return $url;
74
    }
75
}
76
77
/**
78
 * *****************************************************
79
 * LARAVEL STRING HELPERS
80
 * With some adjustments
81
 * *****************************************************
82
 */
83
84
if ( ! function_exists('e'))
85
{
86
    /**
87
     * Escape HTML entities in a string.
88
     *
89
     * @param  string  $value
90
     * @return string
91
     */
92
    function e($value)
93
    {
94
        return htmlentities($value, ENT_QUOTES, 'UTF-8', false);
95
    }
96
}
97
98
if ( ! function_exists('preg_replace_sub'))
99
{
100
    /**
101
     * Replace a given pattern with each value in the array in sequentially.
102
     *
103
     * @param  string  $pattern
104
     * @param  array   $replacements
105
     * @param  string  $subject
106
     * @return string
107
     */
108
    function preg_replace_sub($pattern, &$replacements, $subject)
109
    {
110
        return preg_replace_callback($pattern, function() use (&$replacements)
111
        {
112
            return array_shift($replacements);
113
        }, $subject);
114
    }
115
}
116
117
if ( ! function_exists('snake_case'))
118
{
119
    /**
120
     * Convert a string to snake case.
121
     *
122
     * @param  string  $value
123
     * @param  string  $delimiter
124
     * @return string
125
     */
126
    function snake_case($value, $delimiter = '_')
127
    {
128
        $snakeCache = [];
129
        $key = $value.$delimiter;
130
        if (isset($snakeCache[$key]))
131
        {
132
            return $snakeCache[$key];
133
        }
134
        if ( ! ctype_lower($value))
135
        {
136
            $value = strtolower(preg_replace('/(.)(?=[A-Z])/', '$1'.$delimiter, $value));
137
        }
138
        return $snakeCache[$key] = $value;
139
    }
140
}
141
142
if ( ! function_exists('str_random'))
143
{
144
    /**
145
     * Generate a more truly "random" alpha-numeric string with openssl.
146
     * If openssl_random_pseudo_bytes not exists, use simple legacy function
147
     *
148
     * @param  int  $length
149
     * @return string
150
     *
151
     * @throws \RuntimeException
152
     */
153
    function str_random(int $length = 16)
154
    {
155
        if($length<0){
156
            $length = 16;
157
        }
158
159
        if ( ! function_exists('openssl_random_pseudo_bytes'))
160
        {
161
            return generateRandomString($length);
162
        }
163
        $bytes = openssl_random_pseudo_bytes($length * 2);
164
        if ($bytes === false)
165
        {
166
            throw new RuntimeException('Unable to generate random string.');
167
        }
168
        return substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $length);
169
    }
170
}
171
172
if ( ! function_exists('ends_with'))
173
{
174
    /**
175
     * Determine if a given string ends with a given substring.
176
     *
177
     * @param  string  $haystack
178
     * @param  string|array  $needles
179
     * @return bool
180
     */
181
    function ends_with($haystack, $needles)
182
    {
183 View Code Duplication
        if($haystack===null || $haystack=='' || $needles===null || $needles==''){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
184
            return false;
185
        }
186
187
        foreach ((array) $needles as $needle)
188
        {
189
            if ((string) $needle === substr($haystack, -strlen($needle))) return true;
190
        }
191
        return false;
192
    }
193
}
194
195
if ( ! function_exists('starts_with'))
196
{
197
    /**
198
     * Determine if a given string starts with a given substring.
199
     *
200
     * @param  string  $haystack
201
     * @param  string|array  $needles
202
     * @return bool
203
     */
204
    function starts_with($haystack, $needles)
205
    {
206 View Code Duplication
        if($haystack===null || $haystack=='' || $needles===null || $needles==''){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
207
            return false;
208
        }
209
210 View Code Duplication
        foreach ((array) $needles as $needle)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
211
        {
212
            if ($needle != '' && strpos($haystack, $needle) === 0) return true;
213
        }
214
        return false;
215
    }
216
}
217
218
if ( ! function_exists('str_contains'))
219
{
220
    /**
221
     * Determine if a given string contains a given substring.
222
     *
223
     * @param  string  $haystack
224
     * @param  string|array  $needles
225
     * @return bool
226
     */
227
    function str_contains($haystack, $needles)
228
    {
229 View Code Duplication
        foreach ((array) $needles as $needle)
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
230
        {
231
            if ($needle != '' && strpos($haystack, $needle) !== false) return true;
232
        }
233
        return false;
234
    }
235
}
236
237
if ( ! function_exists('str_finish'))
238
{
239
    /**
240
     * Cap a string with a single instance of a given value.
241
     *
242
     * @param  string  $value
243
     * @param  string  $cap
244
     * @return string
245
     */
246
    function str_finish($value, $cap)
247
    {
248
        $quoted = preg_quote($cap, '/');
249
        return preg_replace('/(?:'.$quoted.')+$/', '', $value).$cap;
250
    }
251
}
252
253
if ( ! function_exists('str_is'))
254
{
255
    /**
256
     * Determine if a given string matches a given pattern.
257
     *
258
     * @param  string  $pattern
259
     * @param  string  $value
260
     * @return bool
261
     */
262
    function str_is($pattern, $value)
263
    {
264
        if ($pattern == $value) return true;
265
        $pattern = preg_quote($pattern, '#');
266
        // Asterisks are translated into zero-or-more regular expression wildcards
267
        // to make it convenient to check if the strings starts with the given
268
        // pattern such as "library/*", making any string check convenient.
269
        $pattern = str_replace('\*', '.*', $pattern).'\z';
270
        return (bool) preg_match('#^'.$pattern.'#', $value);
271
    }
272
}
273
if ( ! function_exists('str_limit'))
274
{
275
    /**
276
     * Limit the number of characters in a string.
277
     *
278
     * @param  string  $value
279
     * @param  int     $limit
280
     * @param  string  $end
281
     * @return string
282
     */
283
    function str_limit($value, $limit = 100, $end = '...')
284
    {
285
        if (mb_strlen($value) <= $limit) return $value;
286
        return rtrim(mb_substr($value, 0, $limit, 'UTF-8')).$end;
287
    }
288
}
289
290
if ( ! function_exists('str_replace_array'))
291
{
292
    /**
293
     * Replace a given value in the string sequentially with an array.
294
     *
295
     * @param  string  $search
296
     * @param  array   $replace
297
     * @param  string  $subject
298
     * @return string
299
     */
300
    function str_replace_array($search, array $replace, $subject)
301
    {
302
        foreach ($replace as $value)
303
        {
304
            $subject = preg_replace('/'.$search.'/', $value, $subject, 1);
305
        }
306
        return $subject;
307
    }
308
}
309
310
if ( ! function_exists('studly_case'))
311
{
312
    /**
313
     * Convert a value to studly caps case.
314
     *
315
     * @param  string  $value
316
     * @return string
317
     */
318
    function studly_case($value)
319
    {
320
        $studlyCache = [];
321
        $key = $value;
322
        if (isset($studlyCache[$key]))
323
        {
324
            return $studlyCache[$key];
325
        }
326
        $value = ucwords(str_replace(array('-', '_'), ' ', $value));
327
        return $studlyCache[$key] = str_replace(' ', '', $value);
328
    }
329
}
330
331
if ( ! function_exists('studly'))
332
{
333
    /**
334
     * Convert a value to studly caps case.
335
     * Alias of studly_case
336
     *
337
     * @param  string  $value
338
     * @return string
339
     */
340
    function studly($value)
341
    {
342
        return studly_case($value);
343
    }
344
}
345
346
if ( ! function_exists('camel_case'))
347
{
348
    /**
349
     * Convert a value to camel case.
350
     *
351
     * @param  string  $value
352
     * @return string
353
     */
354
    function camel_case($value)
355
    {
356
        $camelCache = [];
357
        if (isset($camelCache[$value]))
358
        {
359
            return $camelCache[$value];
360
        }
361
        return $camelCache[$value] = lcfirst(studly($value));
362
    }
363
}
364