hi guys..
in my project i am storing some data in database
in a varchar field with field length 255 characters.

i want to extract only few of these characters that are stored in database..

please help me how can i do that..

Recommended Answers

All 6 Replies

$extract = substr($string, 0, 100);

you will need to use substr(0,10) or regex to search for specific text

Depending on the situation it might be more efficient to use the substring() function in the database query:

$result = mysql_query( 'select substr(myfield,1,10) from mytable' );
Member Avatar for diafol

Thought I'd pop in here. I've been developing multilingual sites for a while, but only recently realised that some sites weren't functioning properly. Investigating, I realised that using substr() and strlen() were failing on non-ASCII characters (e.g. certain accented characters). This is because they are multibyte characters, i.e. most of these take two bytes as opposed to the single byte ACSII chars.
So, if there's a chance that your strings contain non-ASCII chars, use the multibyte alternatives, e.g. mb_substr() and mb_strlen().

In addition, if you restrict a DB varchar field to say 6 characters, text containing multibyte chars may need up to twice that number. Indeed some Asian scripts may need 3x that number. Furthermore, utf8 multibyte strings are planned for 4 bytes, so in theory, db fields may need to be 4x as long as plain ASCII text. Just my 2penneth, as I'm working furiously to fix a couple of old functions...

@ardav: One more reason to use the database instead of the PHP function. The MySQL manual states that substr() is multi-byte safe.

commented: good comment +9
Member Avatar for diafol

@smant: Yes indeed, totally agree. I was referring more to the previous two posts. The SQL version of substr seems a far simpler and appropriate approach as the data is coming straight from the DB.

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.