ale1981 Posted October 29, 2015 Share Posted October 29, 2015 (edited) I have a string e.g. products.0.name and I want to change the string to; products[0][name] I have come up with some code that works but is a bit of a hack, my code is below; var array = field.split("."); field = array[0]+'['+array[1]+']['+array[2]+']'; Is there a better way, I am sure there is using regex? Thanks Edited October 29, 2015 by ale1981 Quote Link to comment https://forums.phpfreaks.com/topic/298906-string-dot-notation-to-brackets/ Share on other sites More sharing options...
Ch0cu3r Posted October 29, 2015 Share Posted October 29, 2015 Your question is not clear are you wanting convert the string 'products.0.name' to the string 'products[0][name]' or are wanting to convert it to array notation so you can return the name item from the array at index 0 of the variable named products? Quote Link to comment https://forums.phpfreaks.com/topic/298906-string-dot-notation-to-brackets/#findComment-1524702 Share on other sites More sharing options...
ale1981 Posted October 29, 2015 Author Share Posted October 29, 2015 Your question is not clear are you wanting convert the string 'products.0.name' to the string 'products[0][name]' or are wanting to convert it to array notation so you can return the name item from the array at index 0 of the variable named products? sorry, yes, i would like the string 'products.0.name' converted to string 'products[0][name]' Quote Link to comment https://forums.phpfreaks.com/topic/298906-string-dot-notation-to-brackets/#findComment-1524715 Share on other sites More sharing options...
Ch0cu3r Posted October 29, 2015 Share Posted October 29, 2015 Your way words just fine. The other way would be to use regex field = field.replace(/(\w+)\.(\d+)\.(\w+)/g, '$1[$2][$3]'); Quote Link to comment https://forums.phpfreaks.com/topic/298906-string-dot-notation-to-brackets/#findComment-1524719 Share on other sites More sharing options...
ale1981 Posted October 30, 2015 Author Share Posted October 30, 2015 (edited) Your way words just fine. The other way would be to use regex field = field.replace(/(\w+)\.(\d+)\.(\w+)/g, '$1[$2][$3]'); Thanks, I knew there would be a regex way, I am just useless when it comes to regex! I am guessing the .replace is quicker as it is done with one function? Edited October 30, 2015 by ale1981 Quote Link to comment https://forums.phpfreaks.com/topic/298906-string-dot-notation-to-brackets/#findComment-1524804 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.