Hi all,
I have a text area, in a form, that only allows basic text and punctuation. I'd like to be able, in certain circumstances, to allow links to be added, in a similar way to the text editors here on daniweb.
Can this be done with php, or do I have to use javascript.

Regards
Taffd

Dani AI

Generated

As described the situation, the interactive "insert link" control belongs in the browser; add a button that runs JavaScript to read the textarea selection, prompt for a URL, and insert either an HTML anchor or a BBCode-style token. PHP should still be used on the server to validate and sanitize every submitted URL or markup before saving or rendering. That separation (client for UX, server for security) keeps the UI responsive while preventing XSS or malformed links.

Minimal JavaScript pattern that works with a plain textarea (replace the prompt with a nicer UI as needed):

function insertLink(textareaId) {
  var ta = document.getElementById(textareaId);
  var start = ta.selectionStart, end = ta.selectionEnd;
  var selected = ta.value.substring(start, end) || 'link';
  var url = prompt('Enter URL (include http:// or https://):', 'http://');
  if (!url) return;
  if (!/^https?:\/\/|^mailto:/.test(url)) { alert('Only http(s) or mailto allowed'); return; }
  var anchor = '<a href="' + url.replace(/"/g, '%22') + '">' + selected + '</a>';
  ta.value = ta.value.slice(0, start) + anchor + ta.value.slice(end);
  ta.selectionStart = ta.selectionEnd = start + anchor.length;
  ta.focus();
}

Server-side checklist and simple PHP checks:

  • Use filter_var($url, FILTER_VALIDATE_URL) and parse_url to allow only safe schemes (http, https, mailto).
  • Escape stored or rendered text with htmlspecialchars when outputting HTML.
  • Prefer storing a safe representation (e.g., plain URL plus link text or BBCode) and convert to HTML at render time with a trusted parser.
  • For old-IE support add a selection-range fallback to the JS.

For a richer editor, a maintained WYSIWYG library (as hinted) saves time. If keeping a lightweight control, the JS+server-validation pattern above is the safest and most portable approach. s point about doing the interactive part client-side aligns with this.

Recommended Answers

All 2 Replies

yes javascript or perhaps flash.

you could not achieve this with php

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.