enter code here
I'm trying to get out ID from link:
www.imdb.com/title/tt5807628/ - > tt5807628
My code in javascript:
var str = "www.imdb.com/title/tt5807628/";
var n = str.search("e/tt");
var res = str.substring(n+2, n+30);
var ukos = res.search("/");
var last = res.substring(0, ukos);
I would like to get the same effect in PHP, how to do it?
Based off my comment here, the following code will just give you the ID:
$id = explode("/", "www.imdb.com/title/tt5807628/")[2];
We use the explode(delimiter, string) function here to break the string at each of the slashes, which creates an index of strings that looks like this:
array (
0 => "www.imdb.com"
1 => "title"
2 => "tt5707627"
)
So, as you can see array index 2 is our ID, so we select that after we break the string (which is the [2] at the end of the variable declaration), leaving us with a variable $id that contains just the ID from the link.
edit:
You could also use parse_url before the explode, just to ensure that
you dont run into http(s):// if the link changes due to user input.
- Keja
$id = explode("/", parse_url("www.imdb.com/title/tt5807628/", PHP_URL_PATH))[2];
With explode function then you can see each part by looping through the array
$varArray = explode( '/', $var );
You can use preg_match as well:
preg_match('~www\.imdb\.com/title/([^/]*)/~', 'www.imdb.com/title/tt5807628/', $matches);
$id = $matches[1];
Related
var login_id = 'sa-testaccount0125#abc.com';
console.log(login_id.substring(0, login_id.lastIndexOf("#")));
Above script works perfectly if I pass input with '#abc.com'. Does not work if string do not have '#domain.com'
We have some user name with username#domain.com and few are just username. I want extract #domain.com from user name. Expected output is if input is username#domain.com return output = username and if input is username, output should be username.
Please help if there is any way.
Use .split() method to split your string in parts
It will still work if you do not have #domain.com
Case-1:
const login_id = 'sa-testaccount0125#abc.com';
console.log(login_id.split("#")[0])
Output
"sa-testaccount0125"
Case-2:
const login_id = 'sa-testaccount0125';
console.log(login_id.split("#")[0])
Output
"sa-testaccount0125"
If you split on # then you get an array of items. The first item of the array will be the username, whether there was a # in it or not.
const test = str => str.split('#')[0]
console.log(test('sa-testaccount0125#abc.com'));
console.log(test('sa-testaccount0125'));
You're already using a indexOf. Usee that to check # if exists as well:
function check(login_id) {
if (login_id.indexOf('#') >= 0) {
return login_id.substring(0, login_id.lastIndexOf("#"));
}
return login_id;
}
console.log(check('sa-testaccount0125#asdasdasd.com'));
console.log(check('sa-asd'));
console.log(check('sa-asasd#domain.com'));
check first if it contains the '#' charactar first
login_id.includes('#') ? console.log(login_id.substring(0,
login_id.lastIndexOf("#"))) : console.log(login_id) ;
Running example
function username(login_id) {
return login_id.includes('#') ? login_id.substring(0,login_id.lastIndexOf("#")) : login_id ;
}
console.log(username("sa-testaccount0125#abc.com")) ;
console.log(username("sa-testaccount0125")) ;
In PHP, how do I convert:
$result = "abdcef";
into an array that's:
$result[0] = a;
$result[1] = b;
$result[2] = c;
$result[3] = d;
Edited
You will want to use str_split().
$result = str_split('abcdef');
http://us2.php.net/manual/en/function.str-split.php
Don't know if you're aware of this already, but you may not need to do anything (depending on what you're trying to do).
$string = "abcdef";
echo $string[1];
//Outputs "b"
So you can access it like an array without any faffing if you just need something simple.
You can use the str_split() function:
$value = "abcdef";
$array = str_split($value);
If you wish to divide the string into array values of different amounts you can specify the second parameter:
$array = str_split($value, 2);
The above will split your string into an array in chunks of two.
$result = "abcdef";
$result = str_split($result);
There is also an optional parameter on the str_split function to split into chunks of x characters.
best you should go for "str_split()", if there is need to manual Or basic programming,
$string = "abcdef";
$resultArr = [];
$strLength = strlen($string);
for ($i = 0; $i < $strLength; $i++) {
$resultArr[$i] = $string[$i];
}
print_r($resultArr);
Output:
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
https://www.php.net/manual/en/function.str-split.php#refsect1-function.str-split-notes
str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string.
Use mb_str_split() instead.
If you need multibyte support in an outdated version of PHP (a version below PHP7.4), then use preg_split() on an empty pattern with a unicode flag. There is no need to slow down the regex engine with a capture group.
Code: (Demo)
var_export(
preg_split('//u', 'abcåäö', 0, PREG_SPLIT_NO_EMPTY)
// or preg_split('/.\K/us', 'abcåäö', 0, PREG_SPLIT_NO_EMPTY)
// or preg_split('/\X\K/u', 'abcåäö', 0, PREG_SPLIT_NO_EMPTY)
);
For any versions of PHP from 7.4 or higher, just use the dedicated function mb_str_split().
mb_str_split('abcåäö')
Output:
array (
0 => 'a',
1 => 'b',
2 => 'c',
3 => 'å',
4 => 'ä',
5 => 'ö',
)
As a warning to researchers using other answers on this page, if you use square brace syntax to access characters by their offset or you use str_split(), you will get broken results when dealing with multibyte characters.
For anyone doing thorough research, I should also mention the \X (unicode version of the dot) respects newline characters by default. \X is slightly different from . without the s modifier. Demo
var_export(preg_split('/.\K/u', "å\nä", 0, PREG_SPLIT_NO_EMPTY)); // element [1] has two characters in it!
echo "\n---\n";
var_export(preg_split('/.\K/us', "å\nä", 0, PREG_SPLIT_NO_EMPTY));
echo "\n---\n";
var_export(preg_split('/\X\K/u', "å\nä", 0, PREG_SPLIT_NO_EMPTY));
With the help of str_split function, you will do it.
Like below::
<?php
$result = str_split('abcdef',1);
echo "<pre>";
print_r($result);
?>
You can use the str_split() function
$array = str_split($string);
foreach ($array as $p){
echo $p . "<br />";
}
str_split() is not safe for multibyte characters.
mb_str_split() requires PHP 7.4+.
Try preg_split() for the rescuse:
$result = preg_split('/(.)/u', 'abcåäö', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
If you tried the above ways and did not get results, try the following method. It worked for my language (Persian and Arabic):
$result = [];
for ( $i = 0; $i < mb_strlen( $string ); ++ $i ) {
$result[] = mb_substr( $string, $i, 1, 'UTF-8' );
}
var_dump($result);
The initial string:
initString = '/digital/collection/music/bunch/of/other/stuff'
What I want: music
Specifically, I want any term (will never include slashes) that would come between collection/ and /bunch
How I'm going about it:
if(initString.includes('/digital/collection/')){
let slicedString = initString.slice(19); //results in 'music/bunch/of/other/stuff'
let indexOfSlash = slicedString.indexOf('/'); //results, in this case, to 5
let desiredString = slicedString.slice(0, indexOfSlash); //results in 'music'
}
Question:
How the heck do I accomplish this in javascript in a more elegant way?
I looked for something like an endIndexOf() that would replace my hardcoded .slice(19)
lastIndexOf() isn't what I'm looking for, because I want the index at the end of the first instance of my substring /digital/collection/
I'm looking to keep the number of lines down, and I couldn't find anything like a .getStringBetween('beginCutoff, endCutoff')
Thank you in advance!
your title says "index" but your example shows you wanting to return a string. If, in fact, you are wanting to return the string, try this:
if(initString.includes('/digital/collection/')) {
var components = initString.split('/');
return components[3];
}
If the path is always the same, and the field you want is the after the third /, then you can use split.
var initString = '/digital/collection/music/bunch/of/other/stuff';
var collection = initString.split("/")[2]; // third index
In the real world, you will want to check if the index exists first before using it.
var collections = initString.split("/");
var collection = "";
if (collections.length > 2) {
collection = collections[2];
}
You can use const desiredString = initString.slice(19, 24); if its always music you are looking for.
If you need to find the next path param that comes after '/digital/collection/' regardless where '/digital/collection/' lies in the path
first use split to get an path array
then use find to return the element whose 2 prior elements are digital and collection respectively
const initString = '/digital/collection/music/bunch/of/other/stuff'
const pathArray = initString.split('/')
const path = pathArray.length >= 3
? pathArray.find((elm, index)=> pathArray[index-2] === 'digital' && pathArray[index-1] === 'collection')
: 'path is too short'
console.log(path)
Think about this logically: the "end index" is just the "start index" plus the length of the substring, right? So... do that :)
const sub = '/digital/collection/';
const startIndex = initString.indexOf(sub);
if (startIndex >= 0) {
let desiredString = initString.substring(startIndex + sub.length);
}
That'll give you from the end of the substring to the end of the full string; you can always split at / and take index 0 to get just the first directory name form what remains.
You can also use regular expression for the purpose.
const initString = '/digital/collection/music/bunch/of/other/stuff';
const result = initString.match(/\/digital\/collection\/([a-zA-Z]+)\//)[1];
console.log(result);
The console output is:
music
If you know the initial string, and you have the part before the string you seek, then the following snippet returns you the string you seek. You need not calculate indices, or anything like that.
// getting the last index of searchString
// we should get: music
const initString = '/digital/collection/music/bunch/of/other/stuff'
const firstPart = '/digital/collection/'
const lastIndexOf = (s1, s2) => {
return s1.replace(s2, '').split('/')[0]
}
console.log(lastIndexOf(initString, firstPart))
I have a very simple PHP array
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
PHP
If I dd($array); out I got
array:3 [▼
"a" => "1"
"b" => "2"
"c" => "3"
]
If I decode dd(json_encode($array));, I got this
"{"a":"1","b":"2","c":"3"}"
JS
I want to be able to access this variable in my Javascript, So I've tried
1
console.log($array);
I got
$array is not defined
2
I'm using Laravel. {{ }} == echo
console.log('{{$array}}');
I got
500 Internal Error
htmlentities() expects parameter 1 to be string, array given (View: /Users/bheng/Sites/portal/resources/views/cpe/index.blade.php)
3
console.log('{{ json_encode($array)}}');
I got
The page to load, but the data is very bad looking
{"a":"1","b":"2","c":"3"}
4
console.log(JSON.parse('{{ json_encode($array)}}'));
I got
Uncaught SyntaxError: Unexpected token & in JSON at position 1
5
console.log(JSON.parse('{{ json_decode($array)}}'));
I got
json_decode() expects parameter 1 to be string, array given
6
console.log('{{ json_decode($array)}}');
I got
json_decode() expects parameter 1 to be string, array given
GOAL
I just want to be able to access my array as Javascript Array or JSON in the Javascript.
Can someone please fill me in on this ?
In Blade, {{ $variable }} will output an escaped version of the string, passed through htmlentities() to make it safe for use in HTML. You want an unescaped version. You can use {!! $variable !!} for that:
console.log({!! json_encode($array) !!});
You don't need to add quotes around it, json_encode() outputs a valid javascript object. It will add quotes where necessary, if you add them yourself you will get the JSON string in your javascript, instead of the JSON object.
In Laravel you can use {!! !!} to skip entity escaping
console.log({!! json_encode($array) !!});
Just echo it as json data and use it in javascript.
<?php
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
?>
<script>var jsArr = <?=json_encode($array);?>;
alert(jsArr);</script>
EDIT because of clarification that you're using blade. Then it should be:
<?php
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
?>
<script>var jsArr = {!! json_encode($array) !!};
alert(jsArr);</script>
{ ... } is an escaped version of your string. But you need the unescapt string. This can be achieved by using {!! ... !!}.
First, you have to understand that PHP run on server side and javascript on client side, as PHP make the response you should print a script like this:
echo "<script>
var sheison = JSON.parse(".dd(json_encode($array)).");
console.log(sheison);
</script>";
I didn't test the code, is just the idea.
ChkNewRspLive.php
<?php
$query3 = "SELECT msgid, id FROM rspnotificationlive WHERE username='{$username1}' ORDER BY id LIMIT 99";
$result3 = mysql_query($query3,$connection) or die (mysql_error());
confirm_query($result3);
$numrspmsg = mysql_num_rows($result3);
echo $numrspmsg . "|";
while($userinfo3 = mysql_fetch_array($result3)){
$rspmsgid= $userinfo3['msgid'];
$msgid= $userinfo3['id'];
echo $rspmsgid . ", ";
}
?>
index.html
<script type="text/javascript">
$.get("ChkNewRspLive.php?username=" + username, function(newrspmsg){
var mySplitResult = newrspmsg.split("|");
var rspMsgCount = parseFloat(mySplitResult[0]);
var rspMsgids =(mySplitResult[1]);
var Msgids = ??//how to get this result from ChkNewRspLive.php ?
});
</script>
As you can see, I used "|" to separate $rspmsgid and $numrspmsg. I also use "," to separate multiple $rspmsgid. How if I want to separate another data $msgid? How to do that?
If I use | to separate $rspmsgid and $msgid, there will be many sign of | because they both are in the while loop.
JSON encode your content.
In your php, change your code to something like:
$json = array();
while($userinfo3 = mysql_fetch_array($result3)){
$rspmsgid= $userinfo3['msgid'];
$msgid= $userinfo3['id'];
$json[] = array($rspmsgid,$msgid);
}
echo json_encode($json);
and then use $.getJson in your javascript.
You won't have to define the number of mysql_rows either, as you can just get that in javascript by using .length on the json data.
edit and escape your string before using it in your SQL!
You are already using the .split() method to seperate the other string. Apply it to the other part and let it split by ", " or just use another | instead of the , and you will have it split into three parts instead of two.
However I suggest you have a look at JSON. This should be the better solution if it gets more complicated.