I got slightly bored, and came up with a ridiculously clunky, though relatively simple and functional, jQuery means of doing this:
$('form').submit(
function() {
var text = $('#text').val().split(' ');
for (i = 0; i < text.length; i++) {
var test = text[i].indexOf('http://www.youtube.com/watch');
if (test != -1) {
text[i] = '[youtube=' + text[i] + ']';
}
}
text = text.join(' ').trim();
$('#text').val(text);
return false;
});
JS Fiddle demo.
Edited to add a necessary sanity check to the function:
$('form').submit(
function() {
var text = $('#text').val().split(' ');
for (i = 0; i < text.length; i++) {
var test = text[i].indexOf('http://www.youtube.com/watch');
var check = text[i].indexOf('[youtube=');
if (test != -1 && check == -1) {
text[i] = '[youtube=' + text[i] + ']';
}
}
text = text.join(' ').trim();
$('#text').val(text);
return false;
});
JS Fiddle of sanity-checking demo.
Basically, in the first function it was possible to simply keep re-submitting the form and prepending '[youtube=' and appending a closing ']'. This latter approach absolves me of some of the stupidity. OF course I could have just checked the the indexOf() value of 'test' is equal to 0, so it was at the beginning of the string. Which I might do, if I revisit this.
Edited because, sometimes, I just can't leave things be...
$('form').submit(
function() {
var text = $('#text').val().split(' ');
for (i = 0; i < text.length; i++) {
var test = text[i].indexOf('http://www.youtube.com/watch');
if (test === 0) {
text[i] = '[youtube=' + text[i] + ']';
}
}
text = text.join(' ').trim();
$('#text').val(text);
return false;
});
Updated JS Fiddle demo.
Edited (again) because I can't leave things be, and because I figured (in the comments) that the jQuery example should be doable in php (more or less directly). And so here it is:
$text = $_POST['text']; // from the textarea of name="text"
$text = explode(" ",$text);
for ($i=0; $i < count($text); $i++) {
if (stripos($text[$i], 'http://www.youtube.com/watch') === 0) {
$text[$i] = '[youtube=' . $text[$i] . ']';
}
}
$text = implode(" ",$text);
I don't know of anywhere that hosts php demos publically, and safely, so I can't demo this, but I think it should work. Although using a foreach() might well have been easier than a for() loop.